I have a simple question that has me stumped:
In a Leaflet application, I have an event listener for clicking elements on the map:
marker.on('click', function () {
doStuff();
$('element').doStuff();
setView(this.getLatLng());
});
However, the setView method also triggers a ‘map moved’ event, which I do not want to fire. Using either plain JavaScript or jQuery, can I prevent any other event from firing while inside the click event function?
Edit: now with a Fiddle! To use it, just click anywhere on the map. As you can see, e.stopPropagation() does not work when placed inside the click event listener.
Advertisement
Answer
I don’t believe you can prevent moveend being fired. (NB: these aren’t jQuery events – Leaflet has its own internal event system.) This is the source for setView:
setView: function (center, zoom) {
zoom = zoom === undefined ? this.getZoom() : zoom;
this._resetView(L.latLng(center), this._limitZoom(zoom));
return this;
}
_resetView always fires moveend at the end:
_resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
var zoomChanged = (this._zoom !== zoom);
if (!afterZoomAnim) {
this.fire('movestart');
if (zoomChanged) {
this.fire('zoomstart');
}
}
...
this.fire('moveend', {hard: !preserveMapOffset});
}
You could investigate customizing these functions to allow for suppression of the event.
Update:
Alternatively, you could change your moveend event handler. Have it track a flag, which you set when you don’t want the normal operations to happen.
For example, you’ll have set up your handler similar to:
map.on('moveend', myHandler);
Have myHandler do something like:
function myHandler(e) {
if (stopFlag) {
return;
}
else {
// Normal operation
...
}
}
Then just enable and disable stopFlag to control the flow. The advantage of this is that you don’t have to publish a custom version of Leaflet with your application.