Reputation: 2962
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 ?
Upvotes: 0
Views: 222
Reputation: 11338
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);
},
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
Upvotes: 1