操作GeoJSON数据 - 在OpenLayers中重新加载矢量图层

3
我正在创建一个函数,用于操作已加载的GeoJSON数据并更新OpenLayers地图。目前我已经可以使用从加载的GeoJSON文件中过滤出来的数据来制作地图。那么我该如何更改矢量图层以使用更新后的数据?
以下是我的代码:
  • load GeoJSON fullGeoJSON:

    var fullGeoJSON = require("./data/data.json");
    
  • create var filteredGeoJSON

    var filteredGeoJSON = {
        "type": "FeatureCollection",
        "features": []
    };
    
  • fill empty features by filtering the fullGeoJSON

    function filterGeoJSON(religion, gender) {
        fullGeoJSON.features.forEach(function (feature) {
            if (
                feature.properties.religion == religion &&
                feature.properties.gender == gender
            ) {
                filteredGeoJSON.features.push(feature);
            }
        });
    }
    
  • define a vector source

    var filteredSource = new VectorSource({
        features: new GeoJSON().readFeatures(filteredGeoJSON, {
            featureProjection: "EPSG:3857"
        })
    });
    
  • define new vector layer using the source

    var filteredLayer = new VectorLayer({
        source: filteredSource
    });
    

使用向量源定义地图(mainMap)。在过滤输入的JSON后,地图可以正常显示仅显示剩余的要素。

现在我正在寻找一种方法,通过单击按钮调用filterGeoJSON()并使用不同的参数更改filteredGeoJSON,并使用此更改后的数据源刷新filteredSource,从而刷新filteredLayer。我目前所拥有的是:

onClick("gender", function () {
    // clear filteredGeoJSON
    (filteredGeoJSON = {
        type: "FeatureCollection",
        features: []
    });
    filterGeoJSON("protestantisch", "f"); // call filterGeoJSON again
    mainMap.refresh(); // <- Something like this?
});

我该如何强制OpenLayers使用来自onClick函数的更改后的filteredGeoJSON作为mainMap的数据源?

谢谢你的帮助!

1个回答

3
您需要更改图层的源以刷新地图内容:
onClick("gender", function() {
   // clear filteredGeoJSON
   filteredGeoJSON = {
      type: "FeatureCollection",
      features: []
   };
   filteredSource = new VectorSource({
      features: filterGeoJSON("protestantisch", "f")
   })
  filteredLayer.setSource(filteredSource);
})

请查看此处

谢谢,虽然文档不是很详细,但setSource函数确实有效! - karkraeg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接