5

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 begining og 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 ?

8

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);  
});
  • Thanks for your answer. I had to calter your code slightly though to fit my code but your idea solved the question. Thanks again – McLan Apr 28 '17 at 14:46
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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