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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:59:36  来源:igfitidea点击:

Changing the style of each feature in a Leaflet GeoJSON layer

javascriptleafletgeojson

提问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 geojsonLayerbased 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 setStyleagain with different values.

是更改 choropleth 以对不同属性进行分类的示例- 技巧是setStyle使用不同的值再次调用。