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

前端 未结 2 785
挽巷
挽巷 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: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.

提交回复
热议问题