Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Last active June 26, 2019 16:07
Show Gist options
  • Save MattSurabian/7868115 to your computer and use it in GitHub Desktop.
Save MattSurabian/7868115 to your computer and use it in GitHub Desktop.
Boilerplate RequireJS module to async load the google maps api and still be able to bundle with rjs. Cooked up with @adamjarret
/**
* GoogleMapsAPI Loader Module
*
* Returns a promise that resolves with the google.maps object when all of the google maps api loading process is complete
*
* Example Usage:
*
* define([ 'app/lib/google-maps-loader' ], function(GoogleMapsLoader){
* GoogleMapsLoader.done(function(GoogleMaps){
* // your google maps code here!
* var geocoder = new GoogleMaps.Geocoder();
* }).fail(function(){
* console.error("ERROR: Google maps library failed to load");
* });
* });
*
* -OR-
*
* define([ 'app/lib/google-maps-loader' ], function(GoogleMapsLoader){
* GoogleMapsLoader.done(function(){
* // your google maps code here!
* var geocoder = new google.maps.Geocoder();
* }).fail(function(){
* console.error("ERROR: Google maps library failed to load");
* });
* });
*
*/
var google_maps_loaded_def = null;
define(['jquery'],function($) {
if(!google_maps_loaded_def) {
google_maps_loaded_def = $.Deferred();
window.google_maps_loaded = function() {
google_maps_loaded_def.resolve(google.maps);
}
require(['http://maps.googleapis.com/maps/api/js?sensor=true&callback=google_maps_loaded'],function(){},function(err) {
google_maps_loaded_def.reject();
//throw err; // maybe freak out a little?
});
}
return google_maps_loaded_def.promise();
});
@MattSurabian
Copy link
Author

Note that this gist sets the sensor param as true, and does not define an API key on the URL. Make sure to adjust the loading url as necessary for your project. Wrote up a blog post about this approach: RequireJS Projects and Asynchronously Loading the Google Maps API

@NouranMahmoud
Copy link

Thanks a lot this helped me easily fix painful issue, but unfortunately it didn't work with Requirejs optimizer.

@fanky10
Copy link

fanky10 commented Feb 29, 2016

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment