Reputation: 1
I create a button to start waiting a click on the map in order to display coordinates. The action (wait to click) can be canceled by any key pressed or by clicking again on the button. Here is the code :
const button = L.Control.extend({
options: { position: "topleft" },
onAdd() {
const myButton = L.DomUtil.create('div');
myButton.innerHTML = "👇";
myButton.className = "mybutton";
myButton.style.width = '30px';
myButton.style.height = '30px';
myButton.style.borderRadius = '5px';
myButton.style.cursor = 'pointer';
myButton.style.border = 'solid 1px #a6a6a6';
myButton.style.padding = '2px';
myButton.style.backgroundColor = '#fff';
myButton.style.fontSize = '20px';
L.DomEvent.on(myButton, "click", (evt) => {
L.DomEvent.stopPropagation(evt);
L.testPointOnMap(evt);
});
return myButton;
}
});
const mybutton = (new button()).addTo(map);
L.testPointOnMap = function (evt) {
var eventHandler = function (evt) {
map._container.style.cursor = '';
console.log(evt?.type, map._events.click, map._events.keyup);
if (!evt)
map.off('click keyup', eventHandler);
else if (evt.type == 'click')
map.off('keyup', eventHandler);
else if (evt.type == 'keyup')
map.off('click', eventHandler);
if (evt?.type == 'click') alert(`click on map : ${evt.latlng.lat}, ${evt.latlng.lng}`);
console.log('after off()', map._events.click, map._events.keyup);
}
if (map._container.style.cursor == 'crosshair') {
eventHandler(); // 2nd button click to cancel
}
else {
map._container.style.cursor = 'crosshair';
map.once('click keyup', eventHandler); // any key to cancel
}
}
The above code can be added directly to the script of a minimal example of Leaflet implementation
The issue is that if I call the eventHandler (manually) on the second click on the button, the .off() function doesn't remove the events listeners from map._events
list.
Stepping in Leaflet Events.js file, it appears that in the function _listens(type, fn, context)
that returns the index of listener, the test listeners[i].fn === fn
returns false in this case, whereas both operands point to the same function !
I don't understand why this happens and don't know if I made a mistake in my code or if it is an abnormal behavior of leaflet ...
Upvotes: 0
Views: 17