2016-04-28 108 views
-1

我有一个函数,重新围绕标记点击时的地图。谷歌地图panTo冲突与addListener

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

回答

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