从传单中的GeoJSON对象动态选择属性

时间:2019-07-09 17:07:16

标签: javascript html leaflet mapping

我正在尝试动态更改我在传单地图上显示的属性。这是我的代码:

$("#button_thermal").click(function(){
$.getJSON("physicalProperties.geojson", function(data) {
var geojson2 = L.geoJson(data, {                
style: { color: 'black', fill: true , opacity: 0.1, fillOpacity:1},
onEachFeature: function (feature,layer){

if (layer.feature.properties.Thermal_Admittance <= 528){
     layer.setStyle({fillColor :'#edf8fb'})
    }
else if (layer.feature.properties.Thermal_Admittance <= 866){
     layer.setStyle({fillColor :'#bfd3e6'})
    }
else if (layer.feature.properties.Thermal_Admittance <= 1205){
     layer.setStyle({fillColor :'#9ebcda'})
    }
else if (layer.feature.properties.Thermal_Admittance <= 1543){
     layer.setStyle({fillColor :'#8c96c6'})
    }
else if (layer.feature.properties.Thermal_Admittance <= 1881){
     layer.setStyle({fillColor :'#8c6bb1'})
    }
else if (layer.feature.properties.Thermal_Admittance <= 2200){
     layer.setStyle({fillColor :'#88419d'})
    }
else if (layer.feature.properties.Thermal_Admittance <= 2500){
     layer.setStyle({fillColor :'#6e016b'})
    }
}
});
geojson2.addTo(map)
$("#button_clear").click(function(){map.removeLayer(geojson2)})
});
});

如何动态将Thermal_Admittance属性更改为其他属性?定义函数后,很容易添加将在调用函数时选择的属性,但是如何将其合并到onEachFeature中定义的函数中呢?

1 个答案:

答案 0 :(得分:0)

欢迎您!

您有2种可能的解决方案:

  • 创建函数构建器
  • 绑定功能

第一个解决方案仅在于制作一个函数,该函数返回另一个函数,并且在构建函数时将属性保留在范围之内:

function buildOnEachFeatureFn(prop) {
  return function (feature, layer) {
    if (feature.properties[prop] <= 528) {
      // etc.
    }
  }
}

L.geoJSON(data, {
  onEachFeature: buildOnEachFeatureFn("Thermal_Admittance")
}

第二种解决方案在某种程度上与以前的解决方案在某种程度上类似,它们在某种程度上也构建了一个新功能,但是使用了bind“魔术”:

function onEachFeatureFn(prop, feature, layer) {
  if (feature.properties[prop] <= 528) {
    // etc.
  }
}

L.geoJSON(data, {
  onEachFeature: onEachFeatureFn.bind(this, "Thermal_Admittance")
}