gpt4 book ai didi

javascript - 延迟以防止 map 拖动时多次调用 ajax

转载 作者:行者123 更新时间:2023-11-27 23:32:43 26 4
gpt4 key购买 nike

每次缩放或拖动 map 时,我都会进行 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
}
});
}

但是,有时用户可能会在处理一个调用时继续拖动或缩放。一个例子是,当用户使用鼠标滚轮时,它会在每个缩放步骤上触发 Zoom_change。

为了防止服务器过载,我想在执行ajax之前添加1或2秒的延迟以等待进一步的缩放或拖动。

我如何在这里实现这个?

最佳答案

使用underscore debounce (或另一个库中的等效项)和空闲事件。

var debouncedLoad = _.debounce(getDataFromServer, 2000/*2 seconds*/);

google.maps.event.addListener(map, 'idle', function() {
debouncedLoad();
});

对于jquery there seems to be a plugin for this

关于javascript - 延迟以防止 map 拖动时多次调用 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34421168/

26 4 0
文章推荐: javascript - 在 ng-bind 内容之前添加 html 元素
文章推荐: javascript - knex js - 一对多关系
文章推荐: javascript - 通过 jQuery 执行键盘命令
文章推荐: javascript - 处理当前
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com