[英]How can I style polygons with parameters inside the FeatureCollection properties on Leaflet?
我有一個 GeoJSON 文件,其中包含FeatureCollection
和Feature
類型。 基本上我的代碼如下(這里的工作示例):
L.geoJSON(myJSON, { style: style }).addTo(mymap);
function style(featureObject) {
return {
fillColor: getColor(featureObject.properties.name),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
}
function getColor(name) {
return name === "name1" ? "#CF8562" :
name === "name2" ? "#FFEDA0" :
"#000000";
}
我的 GeoJSON 結構的一個小樣本如下:
[
{
"type": "FeatureCollection",
"properties": {
"name" : "name1"
},
"features": [
{
"type": "Feature",
"properties": {
"randomParameter" : "text"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-46.6479847244904,
-23.553060554172923
],
[
-46.6479847244904,
-23.553060554172923
],
[
-46.64805562776844,
-23.55318890961171
],
[
-46.64826795788915,
-23.552928264599316
],
[
-46.6479847244904,
-23.553060554172923
]
]
]
}
}]
},
{
"type": "FeatureCollection",
"properties": {
"name" : "name2"
},
"features": [
{
"type": "Feature",
"properties": {
"randomParameter" : "text2"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-46.648050596629034,
-23.55393832474017
],
[
-46.64758222900779,
-23.554141824100373
],
[
-46.64767437978837,
-23.554322319586415
],
[
-46.64814729501603,
-23.55411425749883
],
[
-46.648050596629034,
-23.55393832474017
]
]
]
}
}]
}
]
此代碼無法正常工作,因為它無法識別featureObject.properties.name
值。 此值僅存在於FeatureCollection
中,而不存在於我的 GeoJSON 中的Feature
類型中。 因此,我無法根據 GeoJSON 中的數據為多邊形着色。
我想編輯FeatureCollection
類型下所有元素的樣式。 但是,當我打印 function style
的 object 時,我看到它只看到具有Feature
類型的元素。 我讀過這樣的答案,告訴我們可以編輯FeatureCollection
類型的樣式,但我沒有設法讓它工作。
我想解決這個問題,而不必更改我的 GeoJSON 結構或將FeatureCollection
中的屬性更改為Feature
。 可能嗎? 我可以讓樣式 function 更改FeatureCollection
類型下所有內容的樣式,而不是 GeoJSON 中的Feature
類型嗎?
您可以首先遍歷所有 FeatureCollections 並將屬性復制到子項:
https://jsfiddle.net/falkedesign/9yvb46o5/
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.