How to use Google Maps API with Dojo and AMD

If you are using AMD or RequireJS for your JavaScripts and you would also like to use the Google Maps JavaScript API you have a problem. You can’t just require in the script file and then access the google.maps object from within your script, e.g.:

require(['http://maps.googleapis.com/maps/api/js?client=YOUR_CLIENT_ID'], function() {
    var myMap = new google.maps.Map(mapDiv, mapOptions);
}

This doesn’t work because the map script itself loads another script, which might not have been loaded yet, when you access the google.maps.Map object.

But fortunately, there is a neat loader module by Corey Alix, which solves the problem:

/**
 * Dojo AMD Google Maps Loader Plugin
 * @see https://gist.github.com/ca0v/7450696
 */
define([ 'dojo/_base/kernel'], function(kernel) {
    'use strict';

    var w = kernel.global,
        cb = '_googleApiLoadCallback';

    return {
        load: function(param, req, loadCallback) {
            if (!cb) {
                return;
            }
            w[cb] = function() {
                delete w[cb];
                cb = null;
                loadCallback();
            };
            require([param + "&callback=" + cb]);
        }
    };
});

All you have to do is save the above code as a js file, let’s say gmapLoader.js, and then use it in your dojo code like:

<script type="text/javascript" src="dojo/1.9.3/dojo/dojo.js"></script>
<script type="text/javascript">
require([    
    'yourPath/gmapLoader!http://maps.google.com/maps/api/js?v=3&sensor=false&language=' + dojoConfig.locale,
    'dojo/domReady!'
], function() {
    // access the Maps object
    var myMap = new google.maps.Map(mapDiv, mapOptions);
});

Note: You can use this module not only with the Google Maps JavaScript API, but with any other JavaScript file that loads another script asynchronously. You just have to set the callback variable cb = ‘_googleApiLoadCallback’; to the correct callback function name.

If you want to see the Loader Module in action, check out my photo map search with clustering.

Leave a Reply

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