我正在編寫一個應用程序,它可以通過手動構建的框架異步加載Google Maps。
當我加載地圖時,由於某種原因它不會加載所有的地圖,我將以Uncaught TypeError: undefined is not a function
結束。我檢查了鉻檢查員,發現google.maps
是一個有效的對象,但它沒有自己的屬性。在文檔加載後,我會手動調用「初始化函數」。我究竟做錯了什麼?!異步Google Maps API v3 undefined不是函數
回答
你不能用衆所周知的URL(http://maps.googleapis.com/maps/api/js?v=3&sensor=false)
當你看看腳本文件,你會看到加載地圖的API異步的,這是不是該API被加載,它是一個加載API的加載器。加載器使用document.write()
,在文檔加載完成後調用什麼會導致意外的結果。
此外,文檔的onload事件不會等待異步加載的對象,它可能會過快。
您也不能使用腳本的load-event來調用初始化函數,因爲當它觸發時,加載器被加載,而不是地圖API。
怎麼辦:
追加一個回調參數的腳本URL(用初始化函數的值的名稱)
http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize
現在你會得到一個不同的裝載機,其:
- 不使用
document.write()
- 調用回調functi上(初始化)時,地圖的API已經被加載
演示:http://jsfiddle.net/doktormolle/7cu2F/
相關評論:似乎回調必須是直接連接到窗口的功能。不冷靜的谷歌:)
沒有支持的功能引用使用另一種選擇,the google-API-loader(而不是函數的名稱)。
樣品,其中異步地加載的地圖的API,但只有當存在與文檔中的ID map-canvas
的元素,然後創建地圖:
window.addEventListener('load',function(){
if(document.getElementById('map-canvas')){
google.load("maps", "3",{
callback:function(){
new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(0,0),
zoom: 3
});
}
});
}
},false);
body,html,#map-canvas{
height:100%;
margin:0;
padding:0;
width:100%;
}
<script src="https://www.google.com/jsapi?.js"></script>
<div id="map-canvas"></div>
好的,謝謝你的inf O操作。我不想使用'callback = initialize',因爲我想在初始化函數中傳遞一些額外的參數,但我想我必須解決它。 – Stephen
這正是我所尋找的 – Stephen
似乎'回調'必須是直接附加到窗口的函數。不是很酷的谷歌:) – apneadiving
- 1. Google Maps Api v3 - getBounds is undefined
- 2. Google Maps v3 map.getBounds()。containsLatLng不是函數
- 3. Google Maps Javascript API v3函數getPlace()返回undefined
- 4. Google Maps API v3 - TypeError:表達式結果'google.maps.LatLng'[undefined]不是構造函數
- 5. Google Maps API v3 BrowserIsCompatible
- 6. TypeError:數字不是函數 - 嘗試使用Google Maps API V3 DirectionsService
- 7. Google Maps API v2 vs Google Maps API v3?
- 8. Google Maps API v3不顯示
- 9. Google Maps API v3 - maxZoomService
- 10. google-maps-api-v3 getProjection
- 11. Google Maps API V3:fromContainerPixelToLatLng
- 12. 如何異步添加Google maps v3 API上的標記?
- 13. Google Maps API v3 directions.route()請求
- 14. Google Maps v3 API JS異步 - 多個標記infowindow WordPress的
- 15. google maps api v3 + infoBubble in markerClusterer
- 16. Google Maps API錯誤:initMap不是函數
- 17. Google Maps API a.lat不是函數錯誤
- 18. Google Maps API v3(PHP&Javascript)
- 19. Google Maps API V3 - Javascript問題
- 20. Google Maps API V3 - Internet Explorer
- 21. MVC 4和Google Maps API v3
- 22. kml + google maps api v3 + geoxml3
- 23. Google API V3:computeOffset函數
- 24. Google maps api v3 + marker clusterer:centering map?
- 25. Google Maps Api v3 with jQuery toggle
- 26. Google Maps API V3和Internet Explorer
- 27. MarkerLight for Google Maps API v3
- 28. Google maps API V3方法fitBounds()
- 29. Google Maps JavaScript Places API - URL undefined
- 30. Google Maps API V3返回610,0,0,0
或許有些代碼(你的「手工構建的框架將是一個開始)?一個鏈接到一個頁面展示了這個問題?一個jsfiddle呢? – geocodezip
閱讀文檔是一個好的開始[**請參閱**](https://開發人員。 google.com/maps/documentation/javascript/tutorial#asynch) –