Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  152] [ 3]  / answers: 1 / hits: 15521  / 11 Years ago, mon, april 22, 2013, 12:00:00

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 filter and then refresh the layer.



Is there any way I can update the filter after I have added the data?


More From » leaflet

 Answers
8

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 type
var 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 map
var 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
*/
function showLayer(id) {
var lg = mapLayerGroups[id];
map.addLayer(lg);
}
function hideLayer(id) {
var lg = mapLayerGroups[id];
map.removeLayer(lg);
}

[#78718] Sunday, April 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;