问题
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?
Thanks!
回答1:
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.
来源:https://stackoverflow.com/questions/29146926/mapbox-changing-an-existing-polygons-color