当用户移动地图而不是setCenter方法时捕获bounds_changed事件 [英] Catch bounds_changed event when user moves the map but not the setCenter method
问题描述
我想在用户移动地图时,监听bounds_changed事件,更改缩放但我不想在我的程序调用setCenter或setZoom方法时触发它。所以我在设置中心之前尝试删除事件,然后再次添加它。然而,它没有奏效,我的事件仍然被解雇。
I want to listen 'bounds_changed' event when the user moves the map, changes the zoom but I don't want it to be fired when my program calls setCenter or setZoom methods. So I tried removing event before setting center and adding it after, again. However, it didn't worked, My event is still being fired.
var currentBoundsListener = null;
function addBoundsChangedListener() {
currentBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function () {
// Whatever.
});
}
function setCenter(lat, lng) {
google.maps.event.removeListener(currentBoundsListener);
var geo = new google.maps.LatLng(lat, lng);
map.setCenter(geo);
addBoundsChangedListener();
}
我认为地图正在创建bounds_changed事件后,我添加了新的侦听器,就像事件是异步的。
I think the map is creating bounds_changed event after I add the new listener to it, like the event is asynchronised.
推荐答案
bounds_changed事件确实是异步触发的,所以不是删除侦听器,而是使用指示何时忽略它的全局布尔变量,例如:
The bounds_changed event is indeed fired asynchronously so, instead of removing the listener you could use a global boolean variable that indicates when to ignore it, for example:
var ignore = false; // this var is global;
currentBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function () {
if(ignore) {
ignore = false;
return;
}
// Whatever.
});
function setCenter(lat, lng) {
var geo = new google.maps.LatLng(lat, lng);
ignore = true;
map.setCenter(geo);
}
这篇关于当用户移动地图而不是setCenter方法时捕获bounds_changed事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!