MapBox:更改现有多边形的颜色 [英] MapBox: Changing an existing polygon's color
问题描述
在将MapBox地图上的多边形添加到地图后,我尝试使用以下代码更改其颜色.
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?
谢谢!
推荐答案
使用L.Path
的setStyle
方法,其中L.Polygon
从以下方法扩展:
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'});
在Plunker上的工作示例: http://plnkr.co/edit/vL0rAoKQGhV8zri8mDz7?p=preview
Working example on Plunker: http://plnkr.co/edit/vL0rAoKQGhV8zri8mDz7?p=preview
参考: http://leafletjs.com/reference.html#path-setstyle
如果您真的想通过更改options对象来做到这一点,则需要在之后调用L.Path
的_updateStyle
方法:
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();
但是正如_
所建议的那样,它是L.Path
的内部方法,并且不是API的一部分,因此您应避免使用它,因为它可能会在Leaflet的未来版本中更改.只是认为我应该提一下.
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.
这篇关于MapBox:更改现有多边形的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!