Skip to content
Advertisement

Remove clicked marker Leaflet

I want to create an interactive map in html/js with Leaflet.

I have a function that creates markers on click :

map.on('click', function(e){
    var marker = new L.marker(e.latlng).addTo(map);
    markers.addLayer(marker)
    marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup()
    });

Now, I want to remove markers when I click on them. However, I cannot find the way to do that. Is there a way to fetch marker id and remove it with a specific method ?

Advertisement

Answer

You need to add the event method on() for your markers and do the logic for removing the marker. You can parse the event and do event.target to get a reference to your marker and initially use the remove() method in order to remove the element from the map.

Example:

map.on('click', function(e){
    var marker = new L.marker(e.latlng).addTo(map).on('click', e => e.target.remove());
    markers.addLayer(marker)
    marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup()
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement