2014-01-30 37 views
2

我想在一個只能通過外部JavaScript文件進行編輯的頁面上使用Google Maps API。問題是,當我嘗試使用getScript動態加載Google Maps API時,它無法加載。如何通過JavaScript動態添加Google Maps API?

有什麼方法可以動態加載Google Maps API?

這工作:

http://jsfiddle.net/2XVKL/2/

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

<script> 
function codeAddress() { 

    new google.maps.Geocoder().geocode({'address':document.getElementById('address').value}, function(results, status) { 

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

      alert('worked!'); 

     } 

    }); 

} 
</script> 

<body> 
    <input id="address" type="textbox" value="Sydney, NSW"> 
    <input type="button" value="Submit" onclick="codeAddress()"> 
</body> 

但我需要它的API只使用JavaScript的動態加載,就像這樣:

http://jsfiddle.net/2XVKL/3/

<script> 
$("document").ready(function() { 

    $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"); 

}); 


function codeAddress() { 

    new google.maps.Geocoder().geocode({'address':document.getElementById('address').value}, function(results, status) { 

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

      alert('worked!'); 

     } 

    }); 

} 
</script> 

<body> 
    <input id="address" type="textbox" value="Sydney, NSW"> 
    <input type="button" value="Submit" onclick="codeAddress()"> 
</body> 

編輯:發現這裏的解決方案 - https://gist.github.com/jorgepedret/2432506

+0

這應該是'$(文件).ready',沒有雙引號。 – Blazemonger

回答

1

Google's instructions,你必須添加&callback=initialize到您的網址:

$.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"); 

http://jsfiddle.net/mblase75/dErNs/


要完全安全的,但是,您應該使用.done()使您的功能等到.getScript()完成:

$(document).ready(function() { 
    window.gmap_async = $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"); 
    // global Deferred variable 
}); 

function codeAddress() { 
    window.gmap_async.done(function() { 
     new google.maps.Geocoder().geocode({ 
      'address': document.getElementById('address').value 
     }, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       alert('worked!'); 
      } 
     }); 
    }); 
} 

http://jsfiddle.net/mblase75/dErNs/1/

相關問題