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?