Skip to content Skip to sidebar Skip to footer

Leaflet: Update Geojson Filter?

I would like to populate a GeoJson layer with data and then dynamically filter what features to show. I have gotten the filter function to work but I do not know how to change the

Solution 1:

I did this by adding each feature type to a different LayerGroup based on a property of the feature. e.g.

GeoJSON

var data =[
  {
   type: "Feature",
   properties: {
      type: "type1"
   },
   geometry: {
      type: "Point",
      coordinates: [-1.252,52.107]
   }
  },
  {
   type: "Feature",
   properties: {
      type: "type2"
   },
   geometry: {
      type: "Point",
      coordinates: [-2.252,54.107]
   }
  }
];

Create the GeoJSON Layer

//array to store layers for each feature typevar mapLayerGroups = [];

//draw GEOJSON - don't add the GEOJSON layer to the map here
L.geoJson(data, {onEachFeature: onEachFeature})//.addTo(map);/*
 *for all features create a layerGroup for each feature type and add the feature to the    layerGroup
*/
function onEachFeature(feature, featureLayer) {

    //does layerGroup already exist? if not create it and add to mapvar lg = mapLayerGroups[feature.properties.type];

    if (lg === undefined) {
        lg = new L.layerGroup();
        //add the layer to the map
        lg.addTo(map);
        //store layer
        mapLayerGroups[feature.properties.type] = lg;
    }

    //add the feature to the layer
    lg.addLayer(featureLayer);      
}

Then you can call the Leaflet map.addLayer/removeLayer functions e.g.

//Show layerGroup with feature of "type1"
showLayer("type1");

/*
* show/hide layerGroup   
*/functionshowLayer(id) {
    var lg = mapLayerGroups[id];
    map.addLayer(lg);   
}
functionhideLayer(id) {
    var lg = mapLayerGroups[id];
    map.removeLayer(lg);   
}

Solution 2:

In the GeoJSONaddData method, the first check is if the data is a collection of features, in which case the method gets called for each feature.

Then the filter is applied as follows:

var options = this.options;
if (options.filter && !options.filter(geojson)) { return; }

So if the filter filters out the data when you add it, it does not get stored or remembered anywhere. Changing the filter won't make the data suddenly reappear.

You can keep a reference to the geojson and re-initialize the layer when you change the filter.

Solution 3:

See example below, you have a map and a myBus layer.

map.removeLayer(myBus);

...add your data edit something ...

myBus.addTo(map);

Post a Comment for "Leaflet: Update Geojson Filter?"