[英]Delay to prevent multiple ajax calls on map dragging
I'm making an ajax call every time the map is zoomed or dragged as follows: 每当地图缩放或拖动时,我都会进行ajax调用,如下所示:
function initialize(lat, lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var mapOptions = {
mapTypeControl: false,
center: myLatlng,
zoom: 15,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
getResults(map.getBounds());
});
google.maps.event.addListener(map, 'dragend', function() {
getResults(map.getBounds());
});
};
function getListings(bounds){
data = {'South_Lat':bounds.getSouthWest().lat(), 'South_Lng':bounds.getSouthWest().lng(), 'North_Lat':bounds.getNorthEast().lat(), 'North_Lng':bounds.getNorthEast().lng()};
$.ajax({
type: "POST",
dataType: 'json',
url: "<?=$results_url;?>",
data: data,
success: function (json) {
// do something
}
});
}
However, sometimes users may keep on dragging or zooming while one call is already being processed. 但是,有时用户可能会在已处理一个呼叫的同时继续拖动或缩放。 One example is when the user uses the mouse wheel it triggers the zoom_change on every zoom step.
一个示例是,当用户使用鼠标滚轮时,它将在每个缩放步骤上触发zoom_change。
To prevent overloading the server, I would like to add a 1 or 2 seconds delay to wait for further zooms or drags before executing the ajax. 为了防止服务器过载,我想添加1或2秒的延迟以等待进一步的缩放或拖动,然后再执行ajax。
How can I implement this here? 我如何在这里实现呢?
Use underscore debounce (or an equivalent in another library) and the idle event. 使用下划线去抖动 (或其他库中的下划线 )和idle事件。
var debouncedLoad = _.debounce(getDataFromServer, 2000/*2 seconds*/);
google.maps.event.addListener(map, 'idle', function() {
debouncedLoad();
});
For jquery there seems to be a plugin for this 对于jQuery ,似乎有一个插件
It was a reported bug http://code.google.com/p/gmaps-api-issues/issues/detail?id=1371 . 这是一个已报告的错误http://code.google.com/p/gmaps-api-issues/issues/detail?id=1371 。
Is recommend to use the event "idle". 建议使用事件“ idle”。
google.maps.event.addListener(map, 'idle', function() {
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.