如何通过javascript动态添加Google Maps API?

时间:2014-01-30 20:13:03

标签: javascript jquery google-maps

我正在尝试在一个页面上使用Google Maps API,我只能通过外部javascript文件进行编辑。问题是,当我尝试使用getScript动态加载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>

但是我需要它只使用javascript动态加载api,如下所示:

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

1 个答案:

答案 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!');
            }
        });
    });
}

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