更改Leaflet GeoJSON图层中每个特征的样式

问题描述:

我一直在研究Leaflet Chloropleth example更改Leaflet GeoJSON图层中每个特征的样式

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

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

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

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

+0

这在传单的部分似乎非常复杂。但是谢谢你! – 2014-09-10 20:13:47

要通过@tmcwanswer扩大,战略是一个函数传递给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 
     }); 
    }); 
}