Search code examples
javascriptleafletinteract.js

Leaflet.js with Interact.js --- avoid triggering both click listeners


My page has:

1)a parent div that contains a map (Leaflet.js) and

2)a child div that contains a resizable rectangle (Interactive.js), so that users can select an area.

The rectangle "layer" is on top of the map "layer".

html:

<div id="map">
    <div class="selectBox">
    </div>
</div>

javascript (for initializing the Leaflet map):

var map = L.map('map').setView([0,0], 6);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18
    }).addTo(map);

javascript (for initializing an interactive box with Interact.js)

interact('.selectBox')
.resizable({
preserveAspectRatio: false,
edges: { left: true, right: true, bottom: true, top: true }
})
.on('resizemove', function (event) {
var target = event.target,
    x = (parseFloat(target.getAttribute('data-x')) || 0),
    y = (parseFloat(target.getAttribute('data-y')) || 0);

// update the element's style
target.style.width  = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';

target.style.webkitTransform = target.style.transform =
    'translate(' + x + 'px,' + y + 'px)';

target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
target.textContent = Math.round(event.rect.width) + '?' + Math.round(event.rect.height);
});

The problem is that when the user resizes the interactive rectangle by dragging one of its borders, the map behind also moves. From what I can understand, this is because both Leaflet and Interact catch the onclick event.

I tried:

.on('resizemove', function (event) {
(...)
event.stopPropagation()
event.stopImmediatePropagation()
(...)
}

but none of them worked.

Is there any solution so that the map doesn't move when the user resizes the rectangle?

Thank you!


Solution

  • OK, I figured it out.. I post an answer, in case someone has the same problem:

    The following Leaflet methods (that I was unaware of their existance):

    map.dragging.disable()
    map.dragging.enable()
    

    ...combined with the following Interact events:

    resizestart
    resizeend
    

    ...give the solution:

    .on('resizestart', function (event) {
    map.dragging.disable();
    })
    
    .on('resizeend', function (event) {
    map.dragging.enable();
    })