传单:如何在没有样式属性的GeoJSON对象中设置2000+个点的样式

Leaflet: How to style 2000+ points in a GeoJSON object with no style properties?

本文关键字:样式 GeoJSON 对象 设置 2000+ 属性 传单      更新时间:2023-09-26

我有一个GeoJSON FeatureCollection对象,它包含2000多个功能。在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个类别(每个功能只分配给一个类别)。

在我的情况下使用JavaScriptSwitch语句是一个实用的解决方案吗?或者,有更好的方法吗?

我正在我的代码中做这样的事情:

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功能添加颜色将不必要地增加传输。如果你真的想把它们添加到你的收藏中,你可以在你的收藏对象中创建一些图例属性,比如:

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.标记图标,你应该使用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不支持图标选项。这是一条只支持病理学的路径:

  • http://leafletjs.com/reference.html#path-选项

这里有一个很好的教程创建L.Marker的自定义图标:

  • http://leafletjs.com/examples/custom-icons.html