Google Maps panTo conflicts with addListener

Google Maps panTo conflicts with addListener

本文关键字:with addListener conflicts panTo Maps Google      更新时间:2023-09-26

我有一个函数,可以在单击时将地图重新居中标记。

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进行例外,或者另一种简单的解决方法?谢谢!

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

// 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]);
            }
        }
    });
}