【问题标题】:How to manually load a GeoJSON layer in OpenLayers如何在 OpenLayers 中手动加载 GeoJSON 图层
【发布时间】:2019-08-10 21:49:36
【问题描述】:

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

当我将 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
        })
      });
    }
  });
}

我希望能够传递 loader 而不是 url,这样我就有机会在将响应添加到层之前更改响应。

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

【问题讨论】:

    标签: jquery graphql openlayers geojson


    【解决方案1】:

    readFeatures 只返回一个特征数组。加载器需要将它们添加到源中(在视图投影中)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 2019-04-04
      相关资源
      最近更新 更多