我试图动态加载谷歌 map API。
我正在使用以下代码:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.google.com/jsapi?key=<MY_KEY>;
head.appendChild(script);
但是在尝试创建 map 时
map = new GMap2(document.getElementById("map"));
或者
map = new google.maps.Map2(document.getElementById("map"));
我收到一个错误消息,表明Google(或GMap2)未定义。
最佳答案
你可以这样做。您可以在URL中添加回调函数名称。加载API时将调用它。该回调函数必须在文档范围内可访问。
我前一段时间通过使用jQuery在窗口上触发自定义事件来做到这一点:http://jsfiddle.net/fZqqW/5/
用过“http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback”
window.gMapsCallback = function(){
$(window).trigger('gMapsLoaded');
}
$(document).ready((function(){
function initialize(){
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
function loadGoogleMaps(){
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(window).bind('gMapsLoaded', initialize);
loadGoogleMaps();
})());
Asynchronously Loading the API
You may wish to load the Maps API JavaScript code after your page has finished loading, or on demand. To do so, you can inject your own tag in response to a window.onload event or a function call, but you need to additionally instruct the Maps JavaScript API bootstrap to delay execution of your application code until the Maps JavaScript API code is fully loaded. You may do so using the callback parameter, which takes as an argument the function to execute upon completing loading the API.
The following code instructs the application to load the Maps API after the page has fully loaded (using window.onload) and write the Maps JavaScript API into a tag within the page. Additionally, we instruct the API to only execute the initialize() function after the API has fully loaded by passing callback=initialize to the Maps
在这里查看:https://developers.google.com/maps/documentation/javascript/tutorial
关于google-maps - 动态加载Google Maps api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1398657/