[GIS] Passing values for a geojson filter in Leaflet

geojsonleaflet

I have a situation where I have a geojson layer in leaflet and I want to create a subset of this layer as a separate geojson to highlight specific features. What I am doing right now is passing in the subset manually as form a separate javascript file (the main feature is loaded as a topojson via omnivore). What I want to be able to, however, is pass the features to be included in the "highlight" geojson as an array of key values (or something similar) so that I can define the features to be included from within the script instead of having to manually pass it in externally.

Best Answer

When you initialize the L.geoJson layer group that you will use as argument of Leaflet Omnivore plugin, you can take advantage of the onEachFeature option to copy a reference of your features into other groups, or even to duplicate your features.

var subGroups = [];

var myGroup = L.geoJson(null, {
  onEachFeature: function (feature, layer) {
    var propValue = feature.properties.prop;
    var subGroup = subGroups[propValue];

    // Initialize the subGroup if it does not exist yet.
    if (!subGroup) {
      subGroup = subGroups[propValue] = L.geoJson();
    }

    // Copy a reference of the layer into the subGroup.
    subGroup.addLayer(layer);
    // You could also create a new layer instead of just a reference.
  }
});

Then when Omnivore converts your file, it will add data into myGroup, and for each added feature, the onEachFeature above function will keep a reference in a "sub group" chosen by the propvalue of the feature.