javascript 动态更改传单中多边形的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15606027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically change the color of a polygon in leaflet?
提问by Owen
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:
对于熟悉 Leaflet 的人,您知道一种动态改变多边形颜色的方法吗?例如,以这样定义的圆为例:
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?
代码更改了 window.circle.options.fillColor 的值,但更改并未反映在地图上多边形颜色的更改上。我四处寻找,但没有找到任何东西。有任何想法吗?
Thanks.
谢谢。
回答by tbicr
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'});
L.Circle
扩展L.Path
(http://leafletjs.com/reference.html#path),具有方法setStyle( <Path options> object )
,您可以应用新样式作为window.circle.setStyle({fillColor: '#dddddd'});
回答by Bimal Grg
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
这些选项可用于 geoJson 数据,即:L.geojson()..... :D
So, for polygon . Try,
所以,对于多边形。尝试,
circle.setStyle({
color: 'red'
});
回答by Patrick D
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
});
});
}
}