5

I am trying to use the Google Maps API on a page which I can only edit through an external javascript file. The problem is, when I try to load the Google Maps API dynamically using getScript, it doesn't load.

Is there any way to load the Google Maps API dynamically?

This works:

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>

But I need it the api to be dynamically loaded using only javascript, like this:

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>

Edit: found the solution here - https://gist.github.com/jorgepedret/2432506

1
  • That should be $(document).ready, without the double-quotes. Commented Jan 30, 2014 at 20:26

1 Answer 1

1

Per Google's instructions, you have to add &callback=initialize to your URL:

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

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


To be completely safe, however, you should use .done() to make your function wait until the .getScript() is complete:

$(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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.