Leaflet – Using setStyle() Function for GeoJSON Features

featuresgeojsonleaflet

Ok, since I already asked a very long question about this, but since it didn't get any new replies for a while, and not to get confused in details, I will keep this one simple the best way I can.

If I'm not mistaken, a setStyle function for a named, particular feature would be as follows:

var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
var rect = L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);

rect.setStyle({color: "#4B1BDE"});

…which would change the color from orange to blue. I'm also aware of the resetStyle() function that will revert the style to the original.

This is how I style my GeoJSON:

var everything = L.geoJson(myfile, {
    onEachFeature: function(feature){
        array_of_layers.addLayer(feature);
    },
    style: function(feature){
            switch(feature.properties.name){
            case "belgium": return belgium_style; break;
            case "bosnia": return bosnia_style; break;
            case "denmark": return denmark_style; break;
            case "great_britain": return britain_style; break;
            case "greece": return greece_style; break;
            case "italy": return italy_style; break;
            case "serbia": return serbia_style; break;
            case "spain": return spain_style; break;
            }
    }

});

What I want to do is to make just one country blue and the others gray, later in the code. It's a two-step thing, to paint all countries to gray, and then make one blue.

The first thing is, I need such a loop that would iterate over each feature and setStyle() for all countries to gray. Does it work if I just everything.setStyle({color: "#4B1BDE"}) or something?

The second thing is, (that's giving me sleepless nights) how do I select just one feature out of a group of GeoJSON polygons to work with? Just the country that I need to paint to blue.

If it was a matter of mouse hovering, I could place an event listener as are done in Leaflet tutorials. But regardless of user interaction, I want to set and reset the style by calling it with its name, as I did with the rectangle above.

Best Answer

This works without needing to remove the layer and recreate a new one as described above:

geojson_layer.eachLayer(function (layer) {  
  if(layer.feature.properties.NAME == 'feature 1') {    
    layer.setStyle({fillColor :'blue'}) 
  }
});

It seems to be quite a bit more efficient than removing and recreating the geoJson layer. From the docs, a GeoJSON layer extends FeatureGroup which in turn extends LayerGroup.
Additionally, it seems that each geoJson feature has its own layer in the FeatureGroup!