Google Earth JS API Asynchronous Loading

Unlike a lot of the other Google Maps APIs, the Google Earth JS API doesn’t presently have the ability to load itself asynchronously.  There’s no callback parameter to specify a function to get called when it’s finished loading and initializing which requires most people to load it in <head> every time a page loads.  If you’re only showing the 3D globe in response to some user interaction or other non-default show experience you end up loading a bunch of JavaScript that might never get used (Google Maps for Business customers also incur a page view!).

I pulled together some simple JavaScript which loads the Earth API on demand, letting you specify a success and error callback so you can start drawing your 3D experience when it finishes.  You can find the code here: https://github.com/bamnet/map_sandbox/tree/master/earthAsync.

If you’re curious, the code polls checking every 20ms to see if the JavaScript components like google.earth are available.  When they are your success code runs, if they don’t become available within a certain amount of time (2 seconds), the error code runs so you can try again or wait for your users to be on a faster-connection.

Leave a Reply

Your email address will not be published. Required fields are marked *