Leaflet: How to toggle GeoJSON feature properties from a single collection?

戏子无情 提交于 2019-12-01 01:15:49

You can simply assign your layers within the onEachFeature function. You could even automate the creation of Layer Groups for each category.

Result:

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);

EDIT: replaced overlays to be a mapping instead of an array.

Iterate your GeoJSON collection and create multiple L.GeoJSON layers, one per category and add them as overlays to your L.Control.Layers instance.

var controlLayers = L.control.layers({
    'Street Map': L.mapbox.tileLayer('mapbox.streets').addTo(map)
}).addTo(map);

// Object to store category layers
var overlays = {};

// Iterate the collection
collection.features.forEach(function (feature) {

    var category = feature.properties.category;

    // Check if there's already an overlay for this category
    if (!overlays[category]) {

        // Create and store new layer in overlays object
        overlays[category] = new L.GeoJSON(null, {
            'onEachFeature': function () {},
            'style': function () {}
        });

        // Add layer/title to control
        controlLayers.addOverlay(overlays[category], category); 
    }

    // Add feature to corresponding layer
    overlays[category].addData(feature);
});

Here's an example on Plunker: http://plnkr.co/edit/Zv2xwv?p=preview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!