Mark J. Reeves
Mark J. Reeves

Reputation: 103

Changing an existing of MapBox polygon's color

I'm attempting to use the following code to change the color of a polygon on my MapBox map, after it's already been added to the map.

parishPolygon990 = L.polygon([ vertices ], { color: "#0000FF" }).addTo(map);

console.log(parishPolygon990); // returns #0000FF
console.log(parishPolygon990.options['color']); // returns #0000FF
parishPolygon990.options.color = '#d31603';
console.log(parishPolygon990); // returns #d31603
console.log(parishPolygon990.options['color']); // returns #d31603

You can see that the color value for the polygon updates, but the polygon on the map does not change color.

How can programmatically change the color of the polygon on the map after it's been added?

Upvotes: 0

Views: 1350

Answers (1)

iH8
iH8

Reputation: 28638

Use the setStyle method of L.Path which L.Polygon is extended from:

var polygon = L.polygon([[45,45],[-45,45],[-45,-45],[45,-45]]).addTo(map);

polygon.setStyle({'color': 'yellow'});

Working example on Plunker: http://plnkr.co/edit/vL0rAoKQGhV8zri8mDz7?p=preview

Reference: http://leafletjs.com/reference.html#path-setstyle

If you would really want to do it by changing the options object, you'll need to call the _updateStyle method of L.Path afterwards:

polygon.options.color = 'yellow';
polygon._updateStyle();

But as the _ suggests it's an internal method of L.Path and is not part of the API so you should avoid using it because it can change in future versions of Leaflet. Just thought i should mention it.

Upvotes: 2

Related Questions