3

I am prompting the user to click to create a single point marker on my map. I need to limit this to only one marker (which must be draggable). I have tried using a count variable with a comparison however this condition is not working for me (the user can make many markers - as shown in this image).

enter image description here

Here is my code:

var count = 0;
if (count <= 0) { 
map.on('click', function(e){
    count += 1;
    var marker = L.marker(e.latlng,{draggable: true}).addTo(map);
    var lat = e.latlng.lat;
    var lon = e.latlng.lng;
    alert("Lat, Lon : " + lat + ", " + lon);

    });
}

Thanks in advance.

Worm
  • 1,313
  • 2
  • 11
  • 28
  • 1
    You can remove the listener after it is first called. Here is how you could do that: https://stackoverflow.com/q/1544151/1552587 – Titus Jan 18 '18 at 20:18

1 Answers1

2

You can simply unbind the click event after the first click via off:

var onClick = function(e) {
    map.off('click', onClick);

    var marker = L.marker(e.latlng,{draggable: true}).addTo(map);
    var lat = e.latlng.lat;
    var lon = e.latlng.lng;
    alert("Lat, Lon : " + lat + ", " + lon);
};

map.on('click', onClick);

More info in the Leaflet docs.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94