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

时间:2014-09-10 19:18:58

标签: javascript leaflet geojson

我一直在研究Leaflet Chloropleth example

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

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

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

3 个答案:

答案 0 :(得分:7)

要通过 @tmcw 扩展answer,策略是将函数传递给geojsonLayer.eachLayer(),以更改geojsonLayer中每个要素实例的样式

以下是一些代码,演示了我从 @tmcw 引用的Mapbox example page上发布的代码中提取和简化的策略。我的代码示例根据每个要素实例上指定属性的值更改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
        });
    });
}

答案 1 :(得分:6)

此处an example of changing a choropleth to classify on different properties - 诀窍是再次使用不同的值调用setStyle

答案 2 :(得分:1)

Leaflet 的官方文档解释说:

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

<块引用>

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

<块引用>

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

includes

不幸的是,样式名称不等于 css 样式名称。 例如,使用 'color' 代替 'stroke',使用 'weight' 代替 'stroke-width':

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

相关问题