Google Maps panTo与addListener冲突

时间:2016-04-28 09:46:40

标签: javascript google-maps

我有一个功能,可以在点击时围绕标记重新定位地图。

google.maps.event.addListener(marker, 'click', function() {
  map.panTo(marker.getPosition());
});

但是,这显然会影响我获取标记时的addListener:

google.maps.event.addListener(map, 'idle', function() {
  $.get("/map.json", function(galleries) {
    var bounds = map.getBounds();
    for (var i = 0; i < galleries.length; i++) {
      var latitude = galleries[i].latitude;
      var longitude = galleries[i].longitude;
      var position = new google.maps.LatLng(latitude, longitude)
      if (bounds.contains(position)){
        bindInfobox(map, galleries[i]);
      }
    }
});

有没有办法为addListener做一个例外,或者另外一个简单的方法呢?谢谢!

1 个答案:

答案 0 :(得分:0)

快速解决方法可以在平移地图之前删除事件侦听器,然后在地图完成平移后再次添加事件侦听器。

// add map idle event at load time 
google.maps.event.addListener(map, 'idle', mapIdle);


//remove map idle event and then re-attach the event 
google.maps.event.addListener(marker, 'click', function () {
    google.maps.event.clearListeners(map, 'idle');
    google.maps.event.addListenerOnce(map, 'idle', function () {
        //add the idle event once the map has finised panning
        google.maps.event.addListener(map, 'idle', mapIdle);
    });

    map.panTo(marker.getPosition());       
});

function mapIdle() {
    $.get("/map.json", function (galleries) {
        var bounds = map.getBounds();
        for (var i = 0; i < galleries.length; i++) {
            var latitude = galleries[i].latitude;
            var longitude = galleries[i].longitude;
            var position = new google.maps.LatLng(latitude, longitude)
            if (bounds.contains(position)) {
                bindInfobox(map, galleries[i]);
            }
        }
    });
}