javascript 更改 Leaflet GeoJSON 层中每个要素的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25773389/
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
Changing the style of each feature in a Leaflet GeoJSON layer
提问by Learning stats by example
I have been studying the Leaflet Chloropleth example.
我一直在研究Leaflet Chloropleth 示例。
In my Leaflet application, I have a jQuery dropdown that, when selected, fires a function that takes the name of a state as an argument. I want to use that state name to update the Chloropleth map.
在我的 Leaflet 应用程序中,我有一个 jQuery 下拉列表,当它被选中时,会触发一个以状态名称作为参数的函数。我想使用该州名称来更新 Chloropleth 地图。
What is the pattern for changing the style of a Leaflet GeoJSON layer? Should I recreate the layer I created with L.geoJson()
a second time? It seems as though the layers are drawing on top of each other with that approach.
更改 Leaflet GeoJSON 层样式的模式是什么?我应该重新创建我L.geoJson()
第二次创建的图层吗?似乎这些层是用这种方法在彼此之上绘制的。
I can provide a Fiddle if needed.
如果需要,我可以提供小提琴。
回答by DavidRR
To expand on the answerby @tmcw, the strategy is to pass a function to geojsonLayer.eachLayer()
that changes the style for each feature instance within geojsonLayer
.
为了扩大对答案由@tmcw,该战略是通过一个函数来geojsonLayer.eachLayer()
改变的样式中的每个要素实例geojsonLayer
。
Here is some code that demonstrates this strategy that I lifted and simplified from the code posted on the Mapbox example pagereferenced by @tmcw. My code example changes the style of each of the feature instances within geojsonLayer
based on the value of a specified propertyon each feature instance.
下面是一些演示了这种策略,我抬起并从张贴的代码简化代码Mapbox例如页面通过引用@tmcw。我的代码示例根据每个要素实例geojsonLayer
上的指定属性的值更改其中每个要素实例的样式。
var geojsonLayer = L.geoJson(...); // a GeoJSON layer declared in the outer scope
function restyleLayer(propertyName) {
geojsonLayer.eachLayer(function(featureInstancelayer) {
propertyValue = featureInstanceLayer.feature.properties[propertyName];
// Your function that determines a fill color for a particular
// property name and value.
var myFillColor = getColor(propertyName, propertyValue);
featureInstanceLayer.setStyle({
fillColor: myFillColor,
fillOpacity: 0.8,
weight: 0.5
});
});
}
回答by tmcw
Here's an example of changing a choropleth to classify on different properties- the trick is to call setStyle
again with different values.
这是更改 choropleth 以对不同属性进行分类的示例- 技巧是setStyle
使用不同的值再次调用。