更改Leaflet GeoJSON图层中每个要素的样式

Lea*_*ple 4 javascript geojson leaflet

我一直在研究Leaflet Chloropleth的例子.

在我的Leaflet应用程序中,我有一个jQuery下拉列表,当被选中时,会触发一个以状态名称作为参数的函数.我想使用该州名来更新Chloropleth地图.

更改Leaflet GeoJSON图层样式的模式是什么?我应该重新创建L.geoJson()第二次创建的图层吗?看起来好像这些层是用这种方法绘制在彼此之上的.

如果需要,我可以提供小提琴.

Dav*_*dRR 7

为了扩大对答案@tmcw,该战略是通过一个函数来geojsonLayer.eachLayer()改变的样式中的每个要素实例geojsonLayer.

下面是一些代码,演示了我从@tmcw引用的Mapbox示例页面上发布的代码中提取和简化的策略.我的代码示例根据每个要素实例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
        });
    });
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*fan 7

Leaflet官方文档解释道:

https://leafletjs.com/examples/geojson/

style 选项可用于以两种不同的方式设置要素的样式。首先,我们可以传递一个简单的对象,以相同的方式设置所有路径(折线和多边形)的样式......

或者,我们可以传递一个函数,根据各个特征的属性来设置其样式。在下面的示例中,我们检查“party”属性并相应地设置多边形的样式......

L.geoJSON(states, {
    style: function(feature) {
        switch (feature.properties.party) {
            case 'Republican': return {color: "#ff0000"};
            case 'Democrat':   return {color: "#0000ff"};
        }
    }
}).addTo(map);
Run Code Online (Sandbox Code Playgroud)

不幸的是,样式名称不等于 css 样式名称。例如,使用“颜色”代替“描边”,使用“粗细”代替“描边宽度”:

https://leafletjs.com/reference-1.6.0.html#path-option


tmc*_*mcw 6

这是一个改变一个等值区以对不同属性进行分类的例子 - 诀窍是setStyle再次使用不同的值进行调用.