javascriptleaflet

How can I prevent map.on("click") from firing twice with one touchpad click?


I have a map with code like:

map.on("click", addMarker);

function addMarker(evt) {
    marker = new L.marker(...)
    markerArray.push(marker)
    doSomething()
    if(markerArray.length >= 2){
         alert()
    }
}

And then I recently noticed that the alert was appearing when I first click to create a marker using a touchpad on a laptop (on Ubuntu Firefox, if relevant). When I added a breakpoint before the conditional, the problem didn't happen. But when I added a breakpoint in the conditional, I noticed that the array contained two identical markers. I've searched through my code and can't seem to find an alternate reason for there being multiple map.on("click") listeners or two calls to push a marker to the markerArray, so I think the only explanation is somehow the click map event is calling addMarker twice for a "single click".

How can I make sure addMarker is called only once with "one click"?

Should I do something like the following pseudo-code?

map.on("click", onClick);

function onClick(evt){

    if addMarker not running {
         addMarker(evt)
    }
    //Else do nothing
}
function addMarker(evt) {

Solution

  • A slight tweak from this answer did the trick

    var lastClick = 0;
    
    function addMarker() {
      if (lastClick >= (Date.now() + 20))
        return;
      lastClick = Date.now();
      //....
    }