[GIS] Leaflet: How to add a marker to, or remove it from, a Leaflet map

javascriptleaflet

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?

Best Answer

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