传单:如何从单个集合中切换 GeoJSON 功能属性?

red*_*ift 2 leaflet mapbox

我有一个包含超过 2000 多个功能的 GeoJSON 对象,每个功能都属于一个类别(即“电气”、“军事”等)。总共有大约38个类别。

这是我的集合的架构示例:

{"type":"Feature","properties":{"category":"Electrical","Name":"Plant No 1"},"geometry":{"type":"Point","coordinates":[81.73828125,62.59334083012024]}},{"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]}}
Run Code Online (Sandbox Code Playgroud)

这是我遍历集合的 L.geoJson 函数:

var allPoints = L.geoJson(myCollection, {
    onEachFeature: function(feature, layer){
        layer.bindPopup(L.Util.template(popTemplate, feature.properties));
    },
    "stylel": function(feature){
        return { "color": legend[feature.properties.category]
    }
}}).addTo(map);
Run Code Online (Sandbox Code Playgroud)

如何将每个category属性分配给我的 L.control 函数,以便用户可以打开/关闭集合中的各种类别?如果我将每个类别都设为一个数据集和一个单独的 geoJSOn 层,我就可以做到这一点,但是要完成所有 38 个类别的工作量太大了。

我的尝试:

L.control.layers({
    'Street Map': L.mapbox.tileLayer('mapbox.streets').addTo(map)
},{
    'Electrical': myCollection[feature.properties.category["Electrical"]],
    'Military': myCollection[feature.properties.category["Military"]]
});
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?谢谢!

ghy*_*ybs 5

您可以简单地在onEachFeature函数中分配图层。您甚至可以为每个类别自动创建图层组。

结果:

var categories = {},
    category;

function onEachFeature(feature, layer) {
    layer.bindPopup(L.Util.template(popTemplate, feature.properties));
    category = feature.properties.category;
    // Initialize the category array if not already set.
    if (typeof categories[category] === "undefined") {
        categories[category] = [];
    }
    categories[category].push(layer);
}

// Use function onEachFeature in your L.geoJson initialization.

var overlays = {},
    categoryName,
    categoryArray;

for (categoryName in categories) {
    categoryArray = categories[categoryName];
    overlays[categoryName] = L.layerGroup(categoryArray);
}

L.control.layers(basemaps, overlays).addTo(map);
Run Code Online (Sandbox Code Playgroud)

编辑:替换overlays为映射而不是数组。