2

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) {
raphael
  • 2,762
  • 5
  • 26
  • 55

2 Answers2

3

the "tap" boolean is defaulted as true when map class is created. just set it to false and the event wont fire twice.

i had the same issue where when the map was clicked, two events were fired simultaneously. Just set "tap" to false.

var map = L.map('map', {zoomControl: false, tap: false}).setView([0,0], 3)
//Set "tap" to false
xerxes
  • 31
  • 2
1

A slight tweak from this answer did the trick

var lastClick = 0;

function addMarker() {
  if (lastClick >= (Date.now() + 20))
    return;
  lastClick = Date.now();
  //....
}
Community
  • 1
  • 1
raphael
  • 2,762
  • 5
  • 26
  • 55
  • I ended up storing a reference to the relevant event for my application and just making sure it didn't exist before trying to add it again. This pointed me in the right direction! – Akaisteph7 Mar 28 '23 at 00:37