Thursday 29 September 2016

geojson - Leaflet : filter with condition


I want to insert a condition in a geojson filter. This condition is based in a variable called here varState:






var varState = "Initial value";

var geojsonLayer = L.geoJson(data, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: 5.0,
fillColor: '#e1118e',
color: '#000000',

weight: 1,
opacity: 1.0,
fillOpacity: 1.0
})
},
filter: function(feature, layer) {
if (varState == "01") {
return (feature.properties.field1 == "yes" && feature.properties.field2 == "yes");
}
else if (varState == "02") {

return (feature.properties.field1 == "yes" && feature.properties.field2 == "no");
}
else {
return feature.properties.field1 == "yes";
}
}

var feature_group = new L.featureGroup([]);
feature_group.addLayer(geojsonLayer);
feature_group.addTo(map);


$("#button1").click(function() {
map.removeLayer(geojsonLayer);
varState = "01";
map.addLayer(geojsonLayer);
});

$("#button2").click(function() {
map.removeLayer(geojsonLayer);
varState = "02";

map.addLayer(geojsonLayer);
});

It always return me the last condition despite my varState is 01,02 or null.


Does someone has already succeed this ?



Answer



According to the answer here, Leaflet doesn't "remember" what and whether a layer was filtered, so you need to reinitialise the layer when your filter changes.


Something like this... You'll need to store your data somewhere, and you'll need to call the function from your init function with the default value.


(BTW if you're going to have more than two filters, I'd suggest designing things so you're not hardcoding values in buttons and in filter functions. Create yourself a dictionary of lookup and filter values, load that, then have one button with a dropdown to apply the selected filter. Then all you have to do to add or change filters is change the dictionary and you don't have to touch the code...).


function refilterLayer(varState) {


// remove the layer if it exists - you'll have to look up how to do that

var geojsonLayer = L.geoJson(data, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: 5.0,
fillColor: '#e1118e',
color: '#000000',
weight: 1,

opacity: 1.0,
fillOpacity: 1.0
})
},
filter: function(feature, layer) {
if (varState == "01") {
return (feature.properties.field1 == "yes" && feature.properties.field2 == "yes");
}
else if (varState == "02") {
return (feature.properties.field1 == "yes" && feature.properties.field2 == "no");

}
else {
return feature.properties.field1 == "yes";
}

}).addTo(map);

}

}




// Call the refilter function from the button click event
$("#button1").click(function() {
refilterLayer('01');
});

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...