derdida
derdida

Reputation: 14904

Dynamically load Google Maps API

I would like to load dynamically the google maps api - when I specific element exists on the current page.

When I try to use the geocoder, I get the following message:

ReferenceError: google is not defined

So i think the maps api could not be successfully loaded, but in firebug everything looks fine (the Script gets called correct)

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();

Any ideas? Thank you.

Upvotes: 2

Views: 3599

Answers (2)

derdida
derdida

Reputation: 14904

Thank you for pointing me into the correct direction. Already found out, that google has a example for asyncrounous loading:

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'); 

    }
}

Upvotes: 2

Sonny
Sonny

Reputation: 8336

I've modified your code to run after the script loads:

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);

Upvotes: 2

Related Questions