无法在Openlayers 5中加载Vanilla GeoJSON

时间:2019-04-13 22:21:01

标签: openlayers openlayers-5

我将从使用https://geojson.io构建的一些有效的GeoJSON开始。我的愿望是将其加载到Openlayers 5地图中。

我从this tutorial开始,并尝试使用远程源代替本地源。相关块如下所示:


var map = new Map({
  layers: [
    new TileLayer({
      source: new OSM()
    })
  ],
  target: "map",
  view: new View({
    center: [-13739617.939346, 6179221.917031],
    zoom: 11
  })
});

map.once("postrender", () => {
  axios.get(jsonUrl).then(({ data } = {}) => {
    const jsonSource = new VectorSource({
      features: new GeoJSON().readFeatures(data, {
        featureProjection: "EPSG:4326"
      })
    });

    const jsonLayer = new VectorLayer({
      source: jsonSource,
      style: jsonStyleFunction
    });

    map.addLayer(jsonLayer);
  });
});

当我无法加载时,我能够使用控制台日志来确定断点不是get请求。我还能够看到featureChangeKeys_常量中的jsonSource数量与JSON对象中的功能相同:

featureChangeKeys_:
39: (2) [{…}, {…}]
41: (2) [{…}, {…}]
43: (2) [{…}, {…}]
45: (2) [{…}, {…}]
47: (2) [{…}, {…}]

1 个答案:

答案 0 :(得分:0)

问题是您试图将数据加载到与地图本身不同的坐标参考系统(CRS)中。默认情况下,地图加载在EPSG:3857投影中,而大多数GeoJSON在EPSG:4326中。

您可以通过“寻找空岛”进行测试。将地图平移到latlong(0,0),您可能会看到类似以下的小点:

enter image description here

如果您看到上述类似的小斑点,那么肯定是问题所在。为了解决这个问题,您可以通过如下定义featureProjectiondataProjection属性,让Openlayers快速转换数据:

const jsonSource = new VectorSource({
      features: new GeoJSON().readFeatures(data, {
        dataProjection: "EPSG:4326",
        featureProjection: "EPSG:3857"
      })
    });