我正在尝试在一个页面上使用Google Maps API,我只能通过外部javascript文件进行编辑。问题是,当我尝试使用getScript动态加载Google Maps API时,它无法加载。
有没有办法动态加载Google Maps API?
这有效:
<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>
但是我需要它只使用javascript动态加载api,如下所示:
<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 :(得分: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!');
}
});
});
}