Javascript事件以不受欢迎的顺序触发

时间:2013-02-17 23:04:40

标签: javascript ajax google-maps google-maps-api-3 google-places-api

问题:

当用户将鼠标拖过标记太快时,

mouseout事件会过早触发并导致信息框保持打开状态。换句话说......如果用户快速移入和移出标记... mouseover事件触发,则mouseout事件将触发......但是,执行placesService回调并执行ib.open()被称为。{/ p>

代码:

map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

var request = {
    key: 'for_my_eyes_only',
    location: new google.maps.LatLng(some_lat, some_lng);,
    radius: '500',
    types: ["restaurant"]
};

var service = new google.maps.places.PlacesService(map);
service.search(request, placesCallback);

function placesCallback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {

            var place = results[i];
            var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location,
            });

            //Infobox settings
                var ib = new InfoBox({
                    //a bunch of irrelevant properties.
                });

            google.maps.event.addListener(marker, 'mouseover', markerMouseOverFactory(place, marker, ib));
            google.maps.event.addListener(marker, 'mouseout', markerMouseOutFactory(ib));
        }
    }
}

function markerMouseOverFactory(place, marker, ib){
    return function(){
        var detailService = new google.maps.places.PlacesService(map);
        detailService.getDetails({reference: place.reference}, function(details, status){
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                ib.setContent(/*set some content using details*/);
                ib.open(map, marker);
            }
        });
    }

}

function markerMouseOutFactory(ib){
    return function(){
        ib.close();
    }
}

问题:

有没有办法放弃谷歌地图AJAX请求?如果我可以放弃mouseout监听器中的AJAX请求,那么一切都会好的。或者,你会如何解决这个问题?我尝试在mouseout中使用一个简单的标志,但无法使其正常工作。

1 个答案:

答案 0 :(得分:1)

据我所知,没有方法可以在API中取消请求。但我要做的是延迟在mouseover事件中执行的回调。因此,如果用户持有鼠标超过指定时间;这意味着他/她想要显示infobox

解决方法:

var delayTimer, delay = 800; //less than 1 sec. delay
google.maps.event.addListener(marker, 'mouseover', function() {
    delayTimer = setTimeout(function() { 
        markerMouseOverFactory(place, marker, ib); 
    }, delay);
});

google.maps.event.addListener(marker, 'mouseout', markerMouseOutFactory(ib));
function markerMouseOutFactory(ib){
    clearTimeout(delayTimer); //clear timeout here
    return function(){
        ib.close();
    }
}