Union find
Union find

Reputation: 8150

Changing the style of each feature in a Leaflet GeoJSON layer

I have been studying the Leaflet Chloropleth example.

In my Leaflet application, I have a jQuery dropdown that, when selected, fires a function that takes the name of a state as an argument. I want to use that state name to update the Chloropleth map.

What is the pattern for changing the style of a Leaflet GeoJSON layer? Should I recreate the layer I created with L.geoJson() a second time? It seems as though the layers are drawing on top of each other with that approach.

I can provide a Fiddle if needed.

Upvotes: 14

Views: 27505

Answers (3)

Stefan
Stefan

Reputation: 12260

The official documentation of Leaflet explains that:

https://leafletjs.com/examples/geojson/

The style option can be used to style features two different ways. First, we can pass a simple object that styles all paths (polylines and polygons) the same way ...

Alternatively, we can pass a function that styles individual features based on their properties. In the example below we check the "party" property and style our polygons accordingly ...

L.geoJSON(states, {
    style: function(feature) {
        switch (feature.properties.party) {
            case 'Republican': return {color: "#ff0000"};
            case 'Democrat':   return {color: "#0000ff"};
        }
    }
}).addTo(map);

Unfortunately, the names of the styles are not equal to css style names. For example, instead of 'stroke' use 'color' and instead of 'stroke-width' use 'weight':

https://leafletjs.com/reference-1.6.0.html#path-option

Upvotes: 7

DavidRR
DavidRR

Reputation: 19397

To expand on the answer by @tmcw, the strategy is to pass a function to geojsonLayer.eachLayer() that changes the style for each feature instance within geojsonLayer.

Here is some code that demonstrates this strategy that I lifted and simplified from the code posted on the Mapbox example page referenced by @tmcw. My code example changes the style of each of the feature instances within geojsonLayer based on the value of a specified property on each feature 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
        });
    });
}

restyleLayer('myProperty');

Upvotes: 18

tmcw
tmcw

Reputation: 11882

Here's an example of changing a choropleth to classify on different properties - the trick is to call setStyle again with different values.

Upvotes: 9

Related Questions