Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading google maps asynchronously

Tags:

google-maps

I am trying to load my google map asynchronously and it works but it is loading the map in twice. If I remove "box.onload = initialize;" this stops that problem but then the infobox doesn't show...how do I fix my code so it only loads the map once AND shows the infobox.

function loadScript() {
   var map = document.createElement('script');
   map.type = 'text/javascript';
   map.src = 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=initialize';
   document.body.appendChild(map);  

   map.onload = function() {
      var box = document.createElement('script');
      box.type = 'text/javascript';
      box.src = 'https://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js';
      document.body.appendChild(box);
      box.onload = initialize;
   };
}           
window.onload = loadScript;
like image 957
green_arrow Avatar asked May 02 '13 14:05

green_arrow


People also ask

Is map synchronous JavaScript?

map() is a very useful function but, unfortunately, it only works with synchronous functions. A simple workaround for using async map functions is to use Promose. all() or its more tolerant brother Promise.

How do I turn off Google Maps GUI?

We can disable the default UI controls provided by Google Maps simply by making the disableDefaultUI value true in the map options.

How can I get a free Google map API key?

Go to the Google Maps Platform > Credentials page. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. Click Close.


1 Answers

The map appears twice because you're calling initialize twice.

Before fixing that, let's simplify your code a bit. Never let yourself repeat blocks of code like that; instead make it into a common function.

Also, don't load infobox.js from googlecode.com; Google Code is not a CDN. Load your own copy.

So, the code may look like this:

function addScript( url, callback ) {
    var script = document.createElement( 'script' );
    if( callback ) script.onload = callback;
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild( script );  
}

function loadMapsAPI() {
    addScript( 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=mapsApiReady' );
}

function mapsApiReady() {
    addScript( 'infobox.js', initialize );
}

window.onload = loadMapsAPI;
like image 69
Michael Geary Avatar answered Sep 20 '22 18:09

Michael Geary