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

前端 未结 2 786
挽巷
挽巷 2021-01-07 03:25

I have a single GeoJSON object that contains over 2000+ features and each feature is part of one category (i.e. \"Electrical\", \"Military\", etc). There are a total of abou

相关标签:
2条回答
  • 2021-01-07 03:29

    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

    0 讨论(0)
  • 2021-01-07 03:53

    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.

    0 讨论(0)
提交回复
热议问题