Search code examples
google-mapsdojojs-amd

What is a cleaner way to dynamically load google.maps using AMD?


I'm wanting to take advantage of the google maps loader callback as demonstrated here: https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

I have a working example of doing this using AMD and promises. To load and consume the API:

require(["path/to/google-maps-api-v3"], function (api) {
  api.then(function (googleMaps) {
    // consume the api
   });
});

Here's my module def which I'd prefer return google.maps after it's full loaded instead of a deferred:

define(["dojo/Deferred"], function (Deferred) {
        var d = new Deferred();
        dojoConfig["googleMapsReady"] = function () {
            delete dojoConfig["googleMapsReady"];
            d.resolve(google.maps);
        }
        require(["http://maps.google.com/maps/api/js?v=3&sensor=false&callback=dojoConfig.ipsx.config.googleMapsReady&"]);
        return d;
    });

But solution returns a promise instead of the fully initialized google.maps. I'd prefer it to appear like a regular AMD module but can't see how.


Solution

  • Create an AMD plugin. Here's the one I created based on JanMisker's example:

    define(function () {
        var cb ="_asyncApiLoaderCallback";
        return {
            load: function (param, req, loadCallback) {
                if (!cb) return;
                dojoConfig[cb] = function () {
                    delete dojoConfig[cb];
                    cb = null;
                    loadCallback(google.maps);
                }
                require([param + "&callback=dojoConfig." + cb]);
            }
        };
    });
    

    Usage example:

    require(["plugins/async!//maps.google.com/maps/api/js?v=3&sensor=false"]);