7

Everytime I click on the map I create a draggable marker with a drag function. It works great, however everytime I release the mouse after I dragged some marker, the click event of the map is triggered. How can I stop that ?

map.on('click',
    function (e) {
        var pos = e.latlng;
        console.log('map click event');

        var marker = L.marker(
            pos,
            {
                draggable: true
            }
        );
        marker.on('drag', function (e) {
            console.log('marker drag event');
        });
        marker.on('click', L.DomEvent.stopPropagation);
        marker.addTo(map);
    }
);

Edit: marker.on('click', L.DomEvent.stopPropagation); This partially fixes the bug. Now if I drag the marker VERY quickly and release it, the bug still occurs, because the marker "follows" the mouse cursor in a speed slower than the speed with which I move my cursor, and so when the mouse is released, the mouse is not on the marker anymore, so the map click event is triggered.

1 Answer 1

8

I can confirm that, as you've reported, this appears to be a real bug in both 0.7x and 1.0x (on Chrome, at least; I haven't tested it elsewhere). However, there is a workaround that seems to prevent it. If you name your click event listener function, you can turn it off on dragstart, then use setTimeout to turn it back on a short time after dragend:

map.on('click',
  function mapClickListen(e) {
    var pos = e.latlng;
    console.log('map click event');
    var marker = L.marker(
      pos, {
        draggable: true
      }
    );
    marker.on('drag', function(e) {
      console.log('marker drag event');
    });
    marker.on('dragstart', function(e) {
      console.log('marker dragstart event');
      map.off('click', mapClickListen);
    });
    marker.on('dragend', function(e) {
      console.log('marker dragend event');
      setTimeout(function() {
        map.on('click', mapClickListen);
      }, 10);
    });
    marker.addTo(map);
  }
);

Here's a fiddle to test it:

http://fiddle.jshell.net/nathansnider/sxokLjzb/

3
  • Slick workaround. OSRM seems to have their workaround too. Probably they do the same thing as you.
    – dimitris93
    Commented Apr 18, 2016 at 22:59
  • Actually they have the same bug too ! I reproduced it with a green marker and then dragging in quickly. It places a red marker instead of just moving the green marker.
    – dimitris93
    Commented Apr 18, 2016 at 23:03
  • this workaround won't work for plugin authors because the click event may be from other devs so you can't readd it later :-( Commented Aug 22, 2016 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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