【发布时间】:2011-05-19 07:38:27
【问题描述】:
我有一个带有标记的谷歌地图。我希望在移动/缩放地图时刷新我的标记...
Google 建议为此使用事件bounds_changed,但是当我移动地图时,我移动地图的每个像素都会触发该事件。我希望仅在用户停止移动地图时刷新地图,即当他在拖动后释放鼠标按钮时。
我该怎么做?
【问题讨论】:
标签: javascript google-maps dom-events
我有一个带有标记的谷歌地图。我希望在移动/缩放地图时刷新我的标记...
Google 建议为此使用事件bounds_changed,但是当我移动地图时,我移动地图的每个像素都会触发该事件。我希望仅在用户停止移动地图时刷新地图,即当他在拖动后释放鼠标按钮时。
我该怎么做?
【问题讨论】:
标签: javascript google-maps dom-events
事实证明这是一个报告的错误:http://code.google.com/p/gmaps-api-issues/issues/detail?id=1371。
Google 团队建议使用“idle”事件。例如:
google.maps.event.addListener(map, 'idle', function() {
});
【讨论】:
虽然所选答案最适合大多数情况。如果你想自己控制延迟,你可以简单地使用类似的东西;
var mapupdater;
{....}
google.maps.event.addListener(map, "bounds_changed", mapSettleTime);
function mapSettleTime() {
clearTimeout(mapupdater);
mapupdater=setTimeout(getMapMarkers,500);
}
【讨论】:
添加一个超时,在事件触发 500 毫秒后运行您的代码,每次事件触发都会清除超时并创建一个新的。
google.maps.event.addListener(map, 'bounds_changed', (function () {
var timer;
return function() {
clearTimeout(timer);
timer = setTimeout(function() {
// here goes an ajax call
}, 500);
}
}()));
【讨论】:
您应该检查去抖动功能的工作原理。一个不错的article by Taylor Case 定义如下:
这个函数是为了限制a的次数而构建的 函数被调用 — 滚动事件、鼠标移动事件和按键 事件都是我们可能想要捕捉的事件的很好的例子, 但是如果我们每次都捕获它们可能会很费力 火。
所以你在代码中的某处定义函数:
function debounce(fn, time) {
let timeout;
return function() {
const args = arguments;
const functionCall = () => fn.apply(this, args);
clearTimeout(timeout);
timeout = setTimeout(functionCall, time);
}
}
然后您只需在添加侦听器时使用该函数:
google.maps.event.addListener(myMap, 'bounds_changed', debounce(() => { /* Do something here */ }, 250));
似乎 250 毫秒是在这里使用的好频率。
【讨论】:
尝试同时使用 zoom_changed 和 dragend
【讨论】:
这是一个小 sn-p,它将删除所有多余的 'bound_changed' 调用:
var timeout;
google.maps.event.addListener(map, 'bounds_changed', function () {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
//do stuff on event
}, 500);
}); //time in ms, that will reset if next 'bounds_changed' call is send, otherwise code will be executed after that time is up
【讨论】: