Search code examples
javascriptleaflet

How to correctly use setStyle on a geojson with leaftlet 1.6.0?


I am using leaflet 1.6.0. I want to regurlarly change the color of a geojson which should be done, if not mistaken, with setStyle.

To achieve this, I use an interval, like the following:

        geo_json = L.geoJSON(geo, {
            style: {
                stroke: true,
                color: "black",
                fillColor: "blue"
            }
        }).addTo(map);
        function high(obj) {
            const current_color = obj.options.style.color
            console.log(obj.options.style)
            if (current_color == "black") {
                console.log("to blue")
                obj.setStyle({
                    color: "blue",
                    fillColor: "yellow",
                    stroke: true
                })
            } else {
                console.log("to black")
                obj.setStyle({
                    color: "black",
                    fillColor: "back",
                    stroke: true
                })
            }
        }
        var inter = setInterval(high, 100, geo_json)

However, this does not work.

When going through the high function the first time, the color is correcly set. But during the next iterations, the value of obj.options.style.color is still at "black". As a consequence, it never goes from blue to black again. It seems like the setStyle is not affecing object properties even though it changes its color.

Here is a fiddle.

How should I properly use setStyle to regurlarly update the color of my geojson ?


Solution

  • The problem is that the function setStyle of L.GeoJOSN only changes the style of the child layers and not of it self:

        setStyle: function (style) {
            return this.eachLayer(function (layer) {
                this._setLayerStyle(layer, style);
            }, this);
        },
    

    https://github.com/Leaflet/Leaflet/blob/d6d6051ac6acbc2c68b6b0f8ef1707cf91054f16/src/layer/GeoJSON.js#L148

    If you want to change the style option of the GeoJSON layer you need to update the property manually:

    var newStyle = {
       color: "black",
       fillColor: "back",
       stroke: true
    };
    
    obj.setStyle(newStyle);
    obj.options.style = Object.assign({}, obj.options.style, newStyle); // merge the new style into the old one