[GIS] Remove Leaflet markers _leaflet_id

deleteleaflet

So I want to remove some markers that are created on a button click. If I use map.removeLayer() it removes the layer and also I set the array.length = 0, which resets the containing layer. However, if I run the function again, it shows the same amount of created markers and array elements (fine so far), BUT the _leaflet_id count goes up, as if the previous markers haven't been deleted.

For example,

enter image description here

I just figured this issue out because also the markers are overlapping at the same position, so they appear bold and the browsers slows down.

Any ideas how to solve this? Basically, if I clear the elements, I want to reset the variable and the visualization to zero, i.e the initial state of the map before I create any markers.

SOLUTION

I had to use markers.clearLayers() in order to remove all the layers inside the marker featureGroup. Before I only did map.removeLayer(markers), which does not delete the featureGroup content, but only removes the markers layer

Best Answer

I recommend putting all markers into a layerGroup or a featureGroup, such as:

var markerGroup = L.layerGroup().addTo(map);

Then you add the markers to the group:

L.marker([52.520861, 13.409564]).addTo(markerGroup);

Then you can easily remove the markers from the map by using the removeLayer method on that group.

For example, if you want to remove the marker with the ID 219, then you would have to do the following:

markerGroup.removeLayer(219)
Related Question