38

For anyone who is familiar with Leaflet, do you know a way to dynamically change a polygon's color? For example, take a circle defined like this:

window.circle = L.circle([51.508, -0.11], 500, {
color: 'red',
fillColor: '#ffffff',
    fillOpacity: 0.5
}).addTo(map);

Then later, after a user clicks a button somewhere on an interface (for example), I want to change the color of the circle like this:

window.circle.options.fillColor = "#dddddd";

The code changes the value for window.circle.options.fillColor, but the change is not reflected by a change to the color of the polygon on the map. I've searched around but haven't found anything. Any ideas?

Thanks.

Owen
  • 1,652
  • 2
  • 20
  • 24

3 Answers3

47

L.Circle extends L.Path (http://leafletjs.com/reference.html#path), that have method setStyle( <Path options> object ), and you can apply new style as window.circle.setStyle({fillColor: '#dddddd'});

tbicr
  • 24,790
  • 12
  • 81
  • 106
  • 4
    This seems to work well to change the appearance. However, when I try this it doesn't seem to be reflected in that layer in the code in order for me to save. Am I supposed to somehow update the layer after I set the style? – Josh Jul 16 '15 at 22:31
10

If you are looking for something like this:

const circle = L.circle([lat, lng], {
   style: style,
   onEachFeature: onEachFeature,
});

These options are available for geoJson data ie: L.geojson()..... :D

So, for polygon . Try,

circle.setStyle({
    color: 'red'
});
adhg
  • 10,437
  • 12
  • 58
  • 94
Bimal Grg
  • 7,624
  • 2
  • 24
  • 21
6

I have a set of polygons in my map, this code can change the fillcolor of each polygon dynamically :

// 'file' is a geojson layer
L.geoJSON(file, {
    onEachFeature: colorlayer,
    style: {
        color: "#00008c",
        opacity: 0.6,
        fillColor: '#333333',
        fillOpacity: 0
    }
}).addTo(map);

function colorlayer(feature, layer) {
    layer.on('mouseover', function (e) {
        layer.setStyle({
            fillOpacity: 0.4
        });
    });
    layer.on('mouseout', function (e) {
        layer.setStyle({
            fillOpacity: 0
        });
    });
}
David
  • 5,882
  • 3
  • 33
  • 44
Patrick D
  • 91
  • 1
  • 4