Add a Google Map and Route

In this recipe we’ll add functionality to display and add a route to a Google Map.

For this recipe, we’re only going to use one route on our Google Map. If our route consists of visiting multiple contacts then we’ll add them as ‘waypoints’ along the route. In this way, the route will have a number of legs (for each waypoint/contact) – each leg having its own set of details (e.g. distance/duration). See this Using Google Maps using Waypoints in directions for more details.

Note. The Google Map javaScript library is only loaded into the page (using our GoogleMapsService below) if the user is online (or comes online from being offline). We dynamically add this javascript library to cater for devices going offline and then coming back online.

This codepen demonstrates the code below.

See the Pen RWPavm by Todd Halfpenny (@toddhalfpenny) on CodePen.


The Code

Add the service code

Add the following code to the services.js file.


  • Our GoogleMapsService is only ever using one route, and adding ‘waypoints’ (or legs) along that route for each contact. The route should be regenerated (i.e. callout to Google) each time a contact is added/removed from it. A code example of adding a route can be found in the controllers section below.
  • If you’ve built your app from a MobileCaddy shell or seed app then you may already have the NetworkService – if so, just update your version with the Google related parts from the one below.
  • MobileCaddy uses a local storage item (‘networkStatus’) to determine whether the app is online/offline – and therefore whether the maps can be used or not. This item is set by event listeners setup in app.js (these are included as part of the MobileCaddy shell/seed apps and can be found on the Github repos). The NetworkService and ConnectivityService then make use this local storage item.

Add the HTML and CSS to display map

The following HTML gives an example of how a map might be included in a template. The CSS applied to the elements is displayed below it (and should go in your ‘scss/app.scss’ file).



Add the controller code

The following code snippets give examples of how, and when, the controller might call our GoogleMapsService defined in step 1 above. This code should go in your controllers.js file. (Remember to inject the GoogleMapsService into the controller.

The following code can added to a controller in order to interrogate a route returned from the Google route callout. In the example below, we’re handling the event fired from our GoogleMapsService (when the callback has completed) and using the route data to update distances.