我有一个包含超过2000个功能的GeoJSON FeatureCollection对象。在GeoJSON对象中,每个功能都是一个类别的一部分,如下所示:
{
"type": "Feature",
"properties": {
"category": "Electrical",
"Name": "Plane No 2"
},
"geometry": {
"type": "Point",
"coordinates": [
94.5703125,
58.722598828043374
]
}
},
{
"type": "Feature",
"properties": {
"category": "Military",
"Name": "Base 1"
},
"geometry": {
"type": "Point",
"coordinates": [
104.4140625,
62.91523303947614
]
}
},
在我的实际数据中,总共大约有38个类别(每个功能仅分配给一个类别)。
在我的情况下使用JavaScript Switch语句是否是一种实用的解决方案,以便为每个点提供自己的样式?或者,还有更好的方法?
我在我的代码中做了这样的事情:
L.geoJson(mygeoJson, {
onEachFeature: function (feature, layer){
layer.bindPopup(L.Util.template(popupTemplate, feature.properties));
},
pointToLayer: function (feature, latlng){
return L.circleMarker(latlng, gjsonOptions);
},
// 3 of the 38 categories are listed here as an example
style: function(feature){
switch(feature.properties.category){
case 'Electrical': return { color: '#fb8072'};
case 'Military': return { color: '#b3de69'};
case 'Aviation': return { color: '#80b1d3'};
}
}
}).addTo(map);
我认为应该在客户端添加颜色,就像他/她在代码示例中所做的那样。将颜色添加到每个GeoJSON功能将不必要地使您的传输transfer肿。如果您确实要将它们添加到集合中,则可以在集合对象中创建某种图例属性,如下所示:
var collection = {
"type": "FeatureCollection",
"properties": {
"legend": {
"Electrical": "#fb8072",
"Military": "#b3de69",
"Aviation": "#80b1d3"
}
}
"features": [...]
}
这样,当您创建GeoJSON图层时,可以随时添加它们:
L.geoJson(collection, {
'style': function (feature) {
return {
'color': collection.properties.legend[feature.properties.category]
}
}
}).addTo(map);
您可以将图例存储在代码/脚本中的某个地方,而不是将图例存储在集合对象中:
var legend = {
"Electrical": "#fb8072",
"Military": "#b3de69",
"Aviation": "#80b1d3"
}
L.geoJson(collection, {
'style': function (feature) {
return {
'color': legend[feature.properties.category]
}
}
}).addTo(map);
评论后编辑:
如果需要设置L.Marker图标,则应使用pointToLayer函数:
L.geoJson(collection, {
'pointToLayer': function (feature, latlng) {
return new L.Marker(latlng, {
'icon': new L.Icon({
'iconUrl': 'icons/' + feature.properties.category + '.png'
...
})
})
}
}).addTo(map);
您当前正在使用不支持图标选项的L.CircleMarker。这是一条仅支持pathoptions的路径:
这是有关使用自定义图标创建L.Marker的不错的教程:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句