Async API Google Maps v3 undefined is not a function

I am writing an application that downloads Google Maps asynchronously using a manually created framework.
When I load maps, for some reason it will not load all of this, and I ended up with Uncaught TypeError: undefined is not a function . I checked the chrome inspector and found out that google.maps is a valid object, but it has no properties of its own. I manually call the initialization function after loading the document. What am I doing wrong?!

+27
javascript asynchronous google-maps-api-3
Jan 06 '13 at 17:52
source share
1 answer

You cannot load the asynchronous map API with a known URL ( http://maps.googleapis.com/maps/api/js?v=3&sensor=false )

When you look at the script file, you will see that this is not an API that loads, it is a loader that loads the API. The loader uses document.write() , which will lead to unexpected results when called after loading the document.

In addition, the onload event of the document does not wait for asynchronous downloadable objects; it may be too fast.

You also cannot use the load event for a script to call the initialize function, because when it starts, the loader loads, not the API map.

What to do:
add callback parameter to script -URL (with function name of initialize-function as value)

http://maps.googleapis.com/maps/api/js?v=3&sensor=false& callback=initialize

Now you get another bootloader that:

  • doesn't use document.write()
  • calls the callback function (initialize) when loading the API maps.

Demo: http://jsfiddle.net/doktormolle/7cu2F/




Related to the comment : it seems the callback should be a function directly related to the window. not cool google :)

There is another option google-API-loader , which supports the use of functional links (instead of function names).

An example that loads the maps API asynchronously, but only when there is an element with the identifier map-canvas in the document, and then a map is created:

  window.addEventListener('load',function(){ if(document.getElementById('map-canvas')){ google.load("maps", "3",{ callback:function(){ new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(0,0), zoom: 3 }); } }); } },false); 
  body,html,#map-canvas{ height:100%; margin:0; padding:0; width:100%; } 
 <script src="https://www.google.com/jsapi?.js"></script> <div id="map-canvas"></div> 
+70
Jan 6 '13 at 7:23
source share



All Articles