Worm
Worm

Reputation: 1431

Limiting number of markers that can be created by clicking using leaflet

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.

Upvotes: 3

Views: 939

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

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.

Upvotes: 2

Related Questions