有什么方法可以确定事件是通过编程方式触发还是由用户触发?
我们希望在 map 移动或缩放时重新加载标记列表,但我们最初使用 setBounds()
( http://leafletjs.com/reference.html#rectangle-setbounds ) 设置 map 的边界,这也会触发 moveend
( http://leafletjs.com/reference.html#map-moveend ) 和 zoomend
( http://leafletjs.com/reference.html#map-zoomend ) 事件导致标记重新加载两次。
最佳答案
事件对象上似乎有一个名为 hard
的(未记录的)属性,本地图被 setBounds
移动时,该属性会被设置,而本地图被 setBounds
移动时,该属性不会被设置。用户拖动 map 或使用光标:
map.on('moveend', function (e) {
if (e.hard) {
// moved by bounds
} else {
// moved by drag/keyboard
}
});
Plunker 上的测试用例:http://plnkr.co/edit/SloKuB?p=preview
作为另一个选项,您可以在设置边界后绑定(bind)到事件,这样当您设置边界时它就不会触发,并且当您确实想在之后设置边界时,您可以首先使用 .off< 取消绑定(bind)
并在使用 .on
设置后再次重新绑定(bind)。像(未经测试/hacky)的东西:
function moveEndHandler () {
....
}
map.on('moveend', moveEndHandler);
function mySetBounds (bounds) {
map.off('moveEnd', moveEndHandler);
map.setBounds(bounds);
map.on('moveend', moveEndHandler);
}
关于传单用户触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28614582/