MapBox: Changing an existing polygon's color

三世轮回 提交于 2019-12-12 06:19:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!