Last Updated: February 25, 2016
·
3.623K
· coma

Waiting for the Google Maps API only when it's needed within your AngularJS app

Well, finally my first Coderwall article comes alive!

If you are using the Google Maps API within your AngularJS app, then you probably know that it needs to be fully loaded before being used.

That's why the Google API URL accepts a callback name to be called once is ready; the callback function have to be defined in the window context.

You must delay the bootstraping of your app to ensure that the api will be there before being used... Well, that's a way but what about an app with several routes and only one dependent on the maps api?...

If you are using a router capable of handling resolvers (ngRouter, angular-route-segment or ui-router) then this little sample can help you:

map.js

var googleMaps = {
    ready   : false,
    resolver: {
        map: ['$q', function($q) {

            if (!googleMaps.deferred) {

                googleMaps.deferred = $q.defer();
            }

            if (googleMaps.ready) {

                googleMaps.deferred.resolve();
            }

            return googleMaps.deferred.promise;
        }]
    }
};

window.onGoogleReady = function () {

    googleMaps.ready = true;

    if (googleMaps.deferred) {

        googleMaps.deferred.resolve();
    }
};

app.js (using ui-router)

$stateProvider
        ...
        .state('some.map.state', {
            url        : '/map',
            templateUrl: 'view/some.map.state.html',
            controller : 'some.map.state',
            resolve    : googleMaps.resolver
        })
        ...

Remember to include the scripts in the correct order:

<script src="your/map.js"></script>
<script src="your/app.js"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=onGoogleReady"></script>