Currently, I am working on developing a reusable drop-in Module that can load Google Maps asynchronously and return a promise.
If you want to take a look at the code I have constructed for this using AngularJS, you can find it here.
One issue I have encountered is the drawback of establishing a global callback function "behind the scenes." This could potentially lead to conflicts with other libraries if they happen to use the same namespace.
So, my main question here is whether there is an alternative approach to achieve this functionality without relying on global variables.
Below is a snippet of the code responsible for creating the problematic global callback:
// In order to initialize Google Maps asynchronously, a global function is required
angular.module('GoogleMapsInitializer')
.factory('Initializer', function($window, $q){
// Deferred object for loading maps
var mapsDefer = $q.defer();
// URL for async maps initialization accepting callback function
var asyncUrl = 'https://maps.googleapis.com/maps/api/js?callback=';
// Function for async loading
var asyncLoad = function(asyncUrl, callbackName) {
var script = document.createElement('script');
script.src = asyncUrl + callbackName;
document.body.appendChild(script);
};
// The culprit:
// Callback function - resolves promise once maps are loaded successfully
$window.googleMapsInitialized = function () {
mapsDefer.resolve();
};
// Load Google Maps
asyncLoad(asyncUrl, 'googleMapsInitialized');
return {
// Usage: Initializer.mapsInitialized.then(callback)
mapsInitialized : mapsDefer.promise
};
})