Changing the style of each function in the GeoJSON Leaflet layer
I was looking into Chloropleth Lithography Example .
In my Leaflet app, I have a jQuery dropdown that, when selected, runs a function that takes the name of the state as an argument. I want to use this name to update the Chloropleth map.
What is the template for changing the style of the Leolet GeoJSON layer? Should I create a second layer created with L.geoJson()
? The layers seem to be painting on top of each other using this approach.
I can provide a Fiddle if needed.
source to share
Here's an example of changing choropleth to classify by different properties - the trick is to call again setStyle
with different values.
source to share
To expand on @ tmcw 's answer , the strategy is to pass in a function geojsonLayer.eachLayer()
that changes the style for everyone in the instance geojsonLayer
.
Here's some code that demonstrates this strategy that I have removed and simplified from the code posted on the Mapbox page referenced by @tmcw . My code example changes the style of each function instance in geojsonLayer
based on the value of the specified property for each object instance.
var geojsonLayer = L.geoJson(...); // a GeoJSON layer declared in the outer scope
function restyleLayer(propertyName) {
geojsonLayer.eachLayer(function(featureInstancelayer) {
propertyValue = featureInstanceLayer.feature.properties[propertyName];
// Your function that determines a fill color for a particular
// property name and value.
var myFillColor = getColor(propertyName, propertyValue);
featureInstanceLayer.setStyle({
fillColor: myFillColor,
fillOpacity: 0.8,
weight: 0.5
});
});
}
source to share