Javascript 如何使用传单上FeatureCollection属性中的参数设置多边形的样式?

Javascript 如何使用传单上FeatureCollection属性中的参数设置多边形的样式?,javascript,leaflet,Javascript,Leaflet,我有一个GeoJSON文件,其中包含FeatureCollection和Feature类型。基本上,我的代码如下(): L.geoJSON(myJSON,{style:style}).addTo(mymap); 函数样式(featureObject){ 返回{ fillColor:getColor(featureObject.properties.name), 体重:2, 不透明度:1, 颜色:'白色', dashArray:'3', 填充不透明度:0.7 }; } 函数getColor(名称)

我有一个GeoJSON文件,其中包含
FeatureCollection
Feature
类型。基本上,我的代码如下():

L.geoJSON(myJSON,{style:style}).addTo(mymap);
函数样式(featureObject){
返回{
fillColor:getColor(featureObject.properties.name),
体重:2,
不透明度:1,
颜色:'白色',
dashArray:'3',
填充不透明度:0.7
};
}
函数getColor(名称){
返回名称==“名称1”?“#CF8562”:
名称==“名称2”?“#FFEDA0”:
"#000000";
}
下面是我的GeoJSON结构的一个小示例:

[
{
“类型”:“FeatureCollection”,
“财产”:{
“名称”:“名称1”
},
“特点”:[
{
“类型”:“功能”,
“财产”:{
“随机参数”:“文本”
},
“几何学”:{
“类型”:“多边形”,
“坐标”:[
[
[
-46.6479847244904,
-23.553060554172923
],
[
-46.6479847244904,
-23.553060554172923
],
[
-46.64805562776844,
-23.55318890961171
],
[
-46.64826795788915,
-23.552928264599316
],
[
-46.6479847244904,
-23.553060554172923
]
]
]
}
}]
},
{
“类型”:“FeatureCollection”,
“财产”:{
“名称”:“名称2”
},
“特点”:[
{
“类型”:“功能”,
“财产”:{
“随机参数”:“text2”
},
“几何学”:{
“类型”:“多边形”,
“坐标”:[
[
[
-46.648050596629034,
-23.55393832474017
],
[
-46.64758222900779,
-23.554141824100373
],
[
-46.64767437978837,
-23.554322319586415
],
[
-46.64814729501603,
-23.55411425749883
],
[
-46.648050596629034,
-23.55393832474017
]
]
]
}
}]
}
]
此代码无法正常工作,因为它无法识别
featureObject.properties.name
值。此值仅存在于my GeoJSON中的
FeatureCollection
中,而不存在
功能
类型中。因此,我无法根据GeoJSON中的数据为多边形着色

我想编辑
FeatureCollection
类型下所有元素的样式。但是,当我打印到达
样式
函数的对象时,我看到它只看到具有
功能
类型的元素。我读过这样的回答,比如告诉我我们可以编辑
FeatureCollection
类型的样式,但我没能成功


我想解决这个问题,而不必更改GeoJSON结构或将
FeatureCollection
中的属性更改为
Feature
。可能吗?我是否可以让style函数更改my GeoJSON中
FeatureCollection
类型下所有内容的样式,而不是
Feature
类型?

您可以首先循环所有FeatureCollections并将属性复制到Child:


谢谢,但我认为你的样品上还缺少一个细节。一个方块是黑色的,只有在没有匹配的情况下才会达到这种状态。我在黑色方块(现在是红色)中添加了属性
“name”:“notoverwrited”
,这样您就可以看到,如果存在,它不会覆盖名称。a,我错过了JSON中的细节!这是一个很酷的细节。谢谢
function copyProps(geojson, props){
    var features = L.Util.isArray(geojson) ? geojson : geojson.features,
      i, len, feature;

    if(props && geojson.properties){
      geojson.properties = Object.assign({},props,geojson.properties); // merge properties, if the feature has the same property as the parent, it will not overwritten
    }

    if (features) {
      for (i = 0, len = features.length; i < len; i++) {
        feature = features[i];
        if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
          copyProps(feature, geojson.properties);
        }
      }
    }
  }
copyProps(myJSON);
var layersObj = L.geoJSON(myJSON, { style: style }).addTo(mymap);