2

Is there a possibility to prevent Leaflet dragstart event from triggering just moment after start dragging a marker.

According to Leaflet documentation all you have to do is:

L.DomEvent.on(div, 'click', function (ev) {
    L.DomEvent.stopPropagation(ev);
});

But this obviously will ONLY work for few particular event (e.g. click, dblclick, mouseup, mousedown) because L.DomEvent.stopPropagation(e) and L.DomEvent.preventDefault(e) are just calling e.stopPropagation() and e.preventDefault() respectively otherwise it will try to access the originalEvent object inside the event.

enter image description here

This is the stopPropagation code in Leaflet 1.7.1:

export function stopPropagation(e) {

    if (e.stopPropagation) {
        e.stopPropagation();
    } else if (e.originalEvent) {  // In case of Leaflet event.
        e.originalEvent._stopped = true;
    } else {
        e.cancelBubble = true;
    }
    skipped(e);

    return this;
}

This is everything i tried until now to prevent the Leaflet dragstart event from being firing but no success:

marker.on("dragstart", function (e) {
    if (logic) {
L.DomEvent.stopPropagation(e);
L.DomEvent.preventDefault(e);
L.DomEvent.stop(e);
stopPropagation(e.originalEvent);
preventDefault(e.originalEvent);
stop(e.originalEvent); 
e.originalEvent.stopPropagation();
marker.on("dragstart", L.DomEvent.stopPropagation);
marker.off("dragstart");
marker.bubblingMouseEvents = false;
    }
});

Jsfiddle https://jsfiddle.net/sgf1uxoL/3/

What we need is really the ability to cancel the dragstart event sometimes depending on a logic that we evaluate in the last moment (when the user is about to start dragging) and NOT MAKING THE MARKER NON DRAGGABLE because this would break our design (completely block user from dragging the markers) therefore we don't and we can't use marker.dragging.disable();

2

1 Answer 1

2

Instead of dragstart event, which is fired too late to prevent dragging, you can use mousedown event, which is fired early enough, so that .dragging.disable() method can be used to prevent dragging.

Code could then look something like this:

marker.on('mousedown', function(evt){
  if (dragDisabled) evt.target.dragging.disable();
});
marker.on('mouseup', function(evt){
  if (dragDisabled) evt.target.dragging.enable();
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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