17

On Leaflet, I am drawing a marker everytime the user click on the map like this:

function getClickedLanLon(e) {

    var lat,
        lon,
        zoom;

    lat = e.latlng.lat;
    lon = e.latlng.lng;
    zoom = map.getZoom();

    marker2 = new L.Marker(new L.LatLng(lat, lon));
    map.addLayer(marker2);
}

map.on('click', getClickedLanLon);

but the map get populated with so many markers. Instead, I want to delete the old marker before adding the new one. So, I add the following if condition in the beginning of the function:

if (!map.hasLayer(marker2)) {
   map.removeLayer(marker2);
}

But I get the following error:

Uncaught TypeError: Cannot read property '_leaflet_id' of undefined

My question is how to add a new and remove an old marker every time the user click on the map?

3 Answers 3

30

Try something like this. Put the marker to a variable, and when creating a new one, it the variable already has a value remove it from the map, then draw the new marker.

 var theMarker = {};

  map.on('click',function(e){
    lat = e.latlng.lat;
    lon = e.latlng.lng;

    console.log("You clicked the map at LAT: "+ lat+" and LONG: "+lon );
        //Clear existing marker, 

        if (theMarker != undefined) {
              map.removeLayer(theMarker);
        };

    //Add a marker to show where you clicked.
     theMarker = L.marker([lat,lon]).addTo(map);  
});
0
12

I think the simplest way is to make the Marker as a global variable and change its coordinates instead of deleting it: Marker.setLatLng(lat, lng);

1

The test being used seems incorrect: as shown, it tests for the absence of the layer and deletes it if absent, so the error is entirely reasonable. Try this instead:

if (map.hasLayer(marker2)) {
   map.removeLayer(marker2);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.