2017-08-16 25 views
-1

我有下面的代碼工作正常:谷歌地圖API V3 - 添加多個事件在一張地圖

google.maps.event.addListener(map, 'dragend', function() { 
    bounds = map.getBounds(); 
    var ne = bounds.getNorthEast(); // LatLng of the north-east corner 
    var sw = bounds.getSouthWest(); // LatLng of the south-west corder 
    $.when(removeMarkers()).then(setMarkers(city, state, ne, sw)); 
}); 

當任發生兩個事件之一,該代碼跑到我要的是。我想要的兩個事件是'dragend'和'zoom_changed'。我嘗試了'閒置'事件,它減慢了地圖,並且發生了我不喜歡的事情。這隻會導致糟糕的用戶體驗。然而,'dragend'和'zoom_changed'事件都能很好地工作,我只是沒有找到合併它們的方法。基本上我希望代碼隨時隨地運行,或者放大或縮小。

我曾嘗試這個代碼,我得到那個說「邊界爲空」和它指向的「邊界」的「部分zoom_changed」事件線下方右側的第二個實例的錯誤:

google.maps.event.addListener(map, 'dragend', function() { 
    bounds = map.getBounds(); 
    var ne = bounds.getNorthEast(); // LatLng of the north-east corner 
    var sw = bounds.getSouthWest(); // LatLng of the south-west corder 
    $.when(removeMarkers()).then(setMarkers(city, state, ne, sw)); 
}); 
google.maps.event.addListener(map, 'zoom_changed', function() { 
    bounds = map.getBounds(); 
    var ne = bounds.getNorthEast(); // LatLng of the north-east corner 
    var sw = bounds.getSouthWest(); // LatLng of the south-west corder 
    $.when(removeMarkers()).then(setMarkers(city, state, ne, sw)); 
}); 
+0

我沒有得到與發佈的代碼錯誤([小提琴](http://jsfiddle.net/geocodezip/kv0ewnj3/1/))。請提供證明問題的[mcve]。 – geocodezip

回答

0

如果您要響應多個事件運行完全相同的代碼,將其放入一個命名函數中,並將該函數用作這兩個事件的事件偵聽器。

此外,爲什麼您使用$.when().then()與您的removeMarkers()函數?這是一個異步函數?這將是非常不尋常的。任何刪除某些標記的函數的典型實現都是普通的同步代碼。

所以,你可以寫這樣的代碼:

function updateMarkers() { 
    bounds = map.getBounds(); 
    var ne = bounds.getNorthEast(); 
    var sw = bounds.getSouthWest(); 
    removeMarkers(); 
    setMarkers(city, state, ne, sw); 
} 

google.maps.event.addListener(map, 'dragend', updateMarkers); 
google.maps.event.addListener(map, 'zoom_changed', upateMarkers); 

說了這麼多,我不知道會是導致你跑進了錯誤。你需要發佈一個可運行的測試用例來演示這個問題,無論是在這裏還是在小提琴中。

+0

謝謝邁克爾,你的例子工作。我不確定是什麼導致了這個問題,這是一個非常廣泛的代碼,但這工作。謝謝! – KYLE