Pi-R
Pi-R

Reputation: 654

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 ?

Upvotes: 1

Views: 1824

Answers (1)

Martin
Martin

Reputation: 2414

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()
});

Upvotes: 1

Related Questions