Skip to content

Instantly share code, notes, and snippets.

@backflip
Forked from GFoley83/load-google-maps.js
Last active August 30, 2019 12:03
Show Gist options
  • Select an option

  • Save backflip/8613939 to your computer and use it in GitHub Desktop.

Select an option

Save backflip/8613939 to your computer and use it in GitHub Desktop.
Load Google Maps API using jQuery Deferred
/*!
* JavaScript - loadGoogleMaps( version, apiKey ) - 16/02/2011
*
* - Load Google Maps API using jQuery Deferred.
* Useful if you want to only load the Google Maps API on-demand.
* - Requires jQuery 1.5
*
* Copyright (c) 2011 Glenn Baker
* Dual licensed under the MIT and GPL licenses.
*/
var loadGoogleMaps = (function($) {
var now = jQuery.now();
return function( version, apiKey ) {
//Create a Deferred Object
var deferred = $.Deferred(),
//Declare a resolve function, pass google.maps for the done functions
resolve = function () {
deferred.resolve( google && google.maps ? google.maps : false );
},
//global callback name
callbackName = "loadGoogleMaps_" + ( now++ ),
//Ajax URL params
params;
//If google.maps exists, then Google Maps API was probably loaded with the <script> tag
if( google && google.maps ) {
resolve();
//If the google.load method exists, lets load the Google Maps API in Async.
} else if ( google && google.load ) {
google.load("maps", version || 3, {"other_params": "sensor=false", "callback" : resolve});
//Last, try pure jQuery Ajax technique to load the Google Maps API in Async.
} else {
//Ajax URL params
params = $.extend({
'v': version || 3,
'sensor': false,
'callback': callbackName
}, apiKey ? {"key": apiKey} : {} )
//Declare the global callback
window[callbackName] = function( ) {
resolve();
//Delete callback
setTimeout(function() {
try{
delete window[callbackName];
} catch( e ) {}
}, 20);
};
//Can't use the jXHR promise because 'script' doesn't support 'callback=?'
$.ajax({
dataType: 'script',
data: params,
url: 'http://maps.google.com/maps/api/js'
});
}
return deferred.promise();
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment