google-maps - 动态加载Google Maps api

标签 google-maps dynamic

我试图动态加载谷歌 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/

相关文章:

java - 记忆化是否被视为动态编程?

ios - 在 IOS 的文本字段中自动完成 Google Places

c++ - 将动态数组/矩阵传递给函数进行初始化

MySQL:来自字符串拆分的动态 "IN"子句

android - 哪个 API 真正被贬值 ActivityRecognitionApi 或 ActivityRecognitionClient

python - 动态访问 pandas 数据框的子集,执行计算并写入新数据框

django - Django模型继承层次结构中字段的基于类的默认值

javascript - Google map 商店定位器在面板中显示距离

html - 如何在谷歌地图中指向多个地方

android - 无法在Android上访问Google map