动态加载 Google 地图 API

Dynamically load Google Maps API

我想动态加载 google 地图 api - 当我在当前页面上存在特定元素时。

当我尝试使用地址解析器时,收到以下消息:

ReferenceError: google is not defined

所以我认为地图 api 无法成功加载,但在 firebug 中一切看起来都很好(脚本调用正确)

if ($('.vcard').length > 0) {

    // load google maps when vcard is present

    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "https://maps.google.com/maps/api/js?sensor=false";
    $("head").append(s);

    // error here - unable to use google maps
    var geocoder = new google.maps.Geocoder();

有什么想法吗?谢谢。

我已将您的代码修改为 运行 脚本加载后:

if ($('.vcard').length > 0) {

    // load google maps when vcard is present

    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "https://maps.google.com/maps/api/js?sensor=false";
    s.onload = function() {
        var geocoder = new google.maps.Geocoder();
    };
    $("head").append(s);

感谢您为我指出正确的方向。已经发现,google有一个异步加载的例子:

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
      '&signed_in=true&callback=initialize';
  document.body.appendChild(script);
}

function addGoogleMap() {

    if ($('.vcard').length > 0) {
        loadScript();
    }
}

function initialize() {

    // get the adress
    var CurrentAddress = $('.adr').children().text();

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': CurrentAddress }, function (results, status) {

    if (status == google.maps.GeocoderStatus.OK) { 

        console.log('success'); 

    }
}