简体   繁体   中英

Manipulate GeoJSON Data - reload vector Layer in OpenLayers

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM