简体   繁体   中英

Leaflet remove GeoJSON layer(s)

I'm coloring areas on the map by creating GeoJSON layers in leaflet. First I create an empty layer:

var layerPostalcodes=L.geoJSON().addTo(map);

Then I create a geojson element containing the shape information and add it to the layer:

layerPostalcodes.addData(geojson);

This displays the areas on the map correctly. Now, onclick of a button I'd like to remove all the shapes from the map. This is not working. I've tried several approaches:

layerPostalcodes.clearLayers();

or via a LayerGroup, by adding the GeoJSON layer to it so I can use removeLayer(). But, this does not even display the shapes let alone remove them.

var layerGroup = new L.LayerGroup();
layerGroup.addLayer(layerPostalcodes);
layerGroup.addTo(map);
layerGroup.removeLayer(layerPostalcodes);

What am I doing wrong?

Add the layerGroup to the map before you add the layerPostalCodes to it.

var layerGroup = new L.LayerGroup();
layerGroup.addTo(map);
layerGroup.addLayer(layerPostalcodes);
layerGroup.removeLayer(layerPostalcodes);

Or

var layerGroup = new L.LayerGroup();
layerGroup.addTo(map);
layerGroup.addLayer(layerPostalcodes);
map.removeLayer(layerGroup);

Nothing worked for me so I had a look at the Chrome Developer tool. If you click the highlight element feature and actually click whatever you want to remove, you'll see it's now and element on the page with a class id. So I simply used

 $(".<class name>").remove();

from jQuery and it worked!

For me, nothing worked in this thread and I used @Rastin answer above to come up with a reliable solution:

$(".leaflet-interactive").remove(); //removes previously drawn lines! 

BTW, I had my lines drawn as:

route_lines = L.geoJSON(myLines, { style: myStyle }).addTo(map);

Try this:

map.eachLayer(function (layer) {
            if (layer instanceof L.Polygon) {
                layer.remove()
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM