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

前端 未结 2 783
挽巷
挽巷 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

提交回复
热议问题