Manipulate GeoJSON Data - reload vector Layer in OpenLayers

こ雲淡風輕ζ 提交于 2020-06-17 08:09:19

问题


I’m stuck on creating a function that manipulates loaded GeoJSON data and updates the OpenLayers Map. What I have so far is a map that works with data filtered from a loaded GeoJSON file. How do I change the vector layer to use updated data?

That’s my code so far:

  • 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
    });
    

define map (mainMap) using the vector source. The Map renders fine with only the features shown that are left over after filtering the input JSON

Now I’m looking for a way to change the filteredGeoJSON by the click of a button by calling filterGeoJSON() with different parameters and use this changed data source for refreshing the filteredSource and hence the filteredLayer. What I have so far is:

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

How do I force OpenLayers to use the changed filteredGeoJSON from the onClick function as the datasource for my mainMap?

Thanks for your help!


回答1:


You have to change the layer´s source to refresh the map´s content:

onClick("gender", function() {
   // clear filteredGeoJSON
   filteredGeoJSON = {
      type: "FeatureCollection",
      features: []
   };
   filteredSource = new VectorSource({
      features: filterGeoJSON("protestantisch", "f")
   })
  filteredLayer.setSource(filteredSource);
})

See here.



来源:https://stackoverflow.com/questions/53345234/manipulate-geojson-data-reload-vector-layer-in-openlayers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!