2015-10-20 127 views
3

我在我的網站中使用谷歌地圖版本3。如何檢測谷歌地圖是否成功加載

我遇到了地圖有時無法加載的問題,但相反它會顯示爲灰色框,並且瀏覽器日誌中會顯示錯誤 - 很遺憾,我現在無法獲取日誌,因爲地圖是再次工作。

根據一些研究,這個問題是因爲實驗版我使用

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false"></script> 

有沒有辦法找出如果地圖已成功加載或崩潰,所以我可以告訴用戶很快回來?

P.S.我嘗試了空閒的事件,但即使地圖崩潰,它也被調用。

回答

1

改爲收聽「tilesloaded」事件。這是在地圖(成功)加載並且實際顯示地圖時觸發的最後一個事件。

如果沒有地圖(例如,您沒有明確設置寬度/高度),即使空閒,該事件也不會觸發。

您可以使用Map Events示例,並在「網絡」選項卡中限制您的連接以執行一些測試。 Here是未爲#map設置寬度/高度的示例。

0

在怠速情況下,就下列地圖對象:

檢查以下內容:

使用if (typeof google === 'object' && typeof google.maps === 'object') {...}檢查它是否成功加載。

再檢查if(map.getCenter) { var latlng = map.getCenter(); //check here if latlng is object }

如果有任何的「IF」條件失敗,這意味着什麼是錯的。

1

我認爲最好或最確定的方法是tilesloaded事件和延遲函數的組合,以測試是否設置了「成功標誌」。

/* flag to indicate google maps is loaded */ 
googleMapsLoaded = false; 

/* listen to the tilesloaded event 
    if that is triggered, google maps is loaded successfully for sure */ 
google.maps.event.addListener(map, 'tilesloaded', function() { 
    googleMapsLoaded = true; 
    //clear the listener, we only need it once 
    google.maps.event.clearListeners(map, 'tilesloaded'); 
}); 

/* a delayed check to see if google maps was ever loaded */ 
setTimeout(function() { 
    if (!googleMapsLoaded) { 
    //we have waited 5 secs, google maps is not loaded yet 
    alert('google maps is not loaded'); 
    }  
}, 5000);