2014-08-28 96 views
5

我想跟蹤地圖中心的座標。到目前爲止,我一直在使用它:拖拽完成後獲取中心座標

// On Drag End 
google.maps.event.addListener(map, 'dragend', function() { 
    $('.map_center_coords .latitude').html(map.getCenter().lat()); 
    $('.map_center_coords .longitude').html(map.getCenter().lng()); 
}); 

它通過在拖動事件結束時獲取座標來工作。

問題是我現在使用map.panTo移動到某個位置。

基本上是否有事件"whenever the center has *finished* moving in any way"

正如geocodezip所述,我忘記了center_changed事件。但是,當地圖被拖動/平移時,該事件不斷被觸發。

理想情況下,我正在尋找一個事件,只有在任何拖動/平移完成後纔會觸發一次。

+0

您將需要定義「完成」的含義。沒有這樣的一般事件,你需要自己實現它。 – geocodezip 2014-08-28 03:20:18

回答

7

觀察空閒的事件,而不是(在地圖上變成平移或縮放後閒置這個事件):

google.maps.event.addListener(map,'idle',function(){ 
     if(!this.get('dragging') && this.get('oldCenter') && this.get('oldCenter')!==this.getCenter()) { 
     //do what you want to 
     } 
     if(!this.get('dragging')){ 
     this.set('oldCenter',this.getCenter()) 
     } 

    }); 

    google.maps.event.addListener(map,'dragstart',function(){ 
     this.set('dragging',true);   
    }); 

    google.maps.event.addListener(map,'dragend',function(){ 
     this.set('dragging',false); 
     google.maps.event.trigger(this,'idle',{}); 
    }); 
4

google.maps.Map center_changed事件。

center_changed | None | This event is fired when the map center property changes. 
// On center changed 
google.maps.event.addListener(map, 'center_changed', function() { 
    $('.map_center_coords .latitude').html(map.getCenter().lat()); 
    $('.map_center_coords .longitude').html(map.getCenter().lng()); 
}); 
+0

謝謝,我忘了這個,但實際上它不是我正在尋找的東西。當你在拖着,當你平移的時候,這個連續不斷的發射。理想情況下,我想要一些只有在拖/盤結束後纔會觸發的事情。 (更新問題) – Juicy 2014-08-28 02:31:05

1

嘗試使用idle事件。鏈接到docs

當平移後地圖變爲閒置或 縮放時,會觸發此事件。

如果您希望空閒事件僅在dragend後觸發,請嘗試下面的代碼段。

該代碼在dragendidle事件觸發後將座標輸出到控制檯。

mapObj.addListener('dragend', function() { 
    var idleListener = mapObj.addListener('idle', function() { 
     google.maps.event.removeListener(idleListener); 
     console.log(mapObj.getCenter().lat()); 
     console.log(mapObj.getCenter().lng()); 
    }); 
}); 
+0

如何重置標記位置? – Marco 2017-09-13 15:26:17