Google Maps V3不会删除事件侦听器

时间:2014-03-11 18:15:40

标签: javascript google-maps google-maps-api-3 listener

我对Google Maps API v3有疑问。我正在尝试在缩放更改时删除鼠标悬停监听器。

这是我的代码:

$(document).ready(function() {

    var myOptions = {
        ...
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    function colormaps(map) {
        var newmap = map;
        var piemonteCoords = [
            ...
        ];        
        var piemontePolygon = new google.maps.Polygon({
            ...
        });         
        piemontePolygon.setMap(newmap);
        google.maps.event.addListener(piemontePolygon, 'mouseover', function(event) {
            var prova = event;
            showInfo(prova, newmap, 'Italy');
        });

        google.maps.event.addListener(newmap, 'zoom_changed', function() {
            zoomLevel = map.getZoom();
            if (zoomLevel >= 6) {
                google.maps.event.clearListeners(newmap, 'mouseover');
            }
            else {
                ...
            }
        } //fine colormaps
        google.maps.event.addDomListener(window, 'load', colormaps(map));
    });

当缩放达到目标级别时,不会删除侦听器。怎么了?

1 个答案:

答案 0 :(得分:7)

您正在向piemontePolygon对象添加监听器,但是您要从newmap对象清除它,这可能是错误的(我不是该领域的专家)所以我无法确定。

尝试这样做:

google.maps.event.clearListeners(piemontePolygon, 'mouseover');


修改
根据{{​​3}},如果上面的代码失败,你可以尝试另一种方法。


案例1(您也可以将事件类型作为第二个参数传递):

google.maps.event.clearInstanceListeners(piemontePolygon);


案例2:

var listener1 = google.maps.event.addListener(piemontePolygon, 'mouseover', function(
    var prova = event;
    showInfo(prova, newmap, 'Italy')
});

google.maps.event.removeListener(listener1);