如何在OpenLayers中手动加载GeoJSON图层

时间:2019-08-10 21:49:36

标签: jquery graphql openlayers geojson

我正在尝试从URL加载一些GeoJSON。

当我将size: 15 type: "application/octet-stream" 传递给向量源时,一切都会按预期进行:

url

但是,当我通过function aircraftLayerFunction() { var format = new ol.format.GeoJSON(); return new ol.layer.Vector({ source: new ol.source.Vector({wrapX: false, url:"/aircraft", format: format}), style: function (feature, resolution) { return new ol.style.Style({ image: new ol.style.Circle({ radius: 3, fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.1)'}), stroke: new ol.style.Stroke({color: 'red', width: 1}) }), text: new ol.style.Text({ text: feature.get('name'), offsetY: 8 }) }); } }); } 时,却什么也没得到,甚至在控制台上也没有错误消息:

loader

我希望能够传递一个function aircraftLayerFunction() { var format = new ol.format.GeoJSON(); return new ol.layer.Vector({ source: new ol.source.Vector({wrapX: false, format: format, loader: function(extent, resolution, projection) { $.getJSON("/aircraft", function(response) { format.readFeatures(response) }); } }), style: function (feature, resolution) { return new ol.style.Style({ image: new ol.style.Circle({ radius: 3, fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.1)'}), stroke: new ol.style.Stroke({color: 'red', width: 1}) }), text: new ol.style.Text({ text: feature.get('name'), offsetY: 8 }) }); } }); } 而不是一个url,以便我有机会在将其要素添加到图层之前更改响应。

特别是,我想使用GraphQL将我的loader REST端点替换为更灵活的东西。但是GraphQL一直在我的响应中添加“数据”和“飞机”节点...

1 个答案:

答案 0 :(得分:1)

readFeatures仅返回一组功能。加载程序需要将它们添加到源中(在视图投影中)

  loader: function(extent, resolution, projection) {
    var source = this;
    $.getJSON("/aircraft", function(response) {
      source.addFeatures(format.readFeatures(response, { featureProjection: projection }));
    });
  }