Ionic Google Maps Example

Part 1: Integrating Google Maps with an Ionic 1.x Application



·

Google Maps and mobile apps are a perfect match. The Google Maps API is an awesome piece of tech by itself, but when you couple it with a device that is meant to be mobile, as in not stationary, it opens up a wide range of possibilities. There’s a ton of cool apps out there today that utilise Google Maps to do all kinds of things.

Even if maps aren’t the core feature of your application, they are often quite useful as supplementary features as well (displaying the location of your business on a map for example).

In this tutorial I am going to walk you through how to integrate the Google Maps JavaScript SDK into an Ionic application.

Generate a New Ionic Application

First things first, let’s generate a new Ionic application.

Run the following command to generate a new Ionic application

ionic start ionic-maps blank

As always, it’s a good idea to set up SASS right away as well.

Run the following command inside of your new project to set up SASS

ionic setup sass

Although the functionality we are adding will work through the browser, we will be using a native plugin for geolocation when it is available, so let’s also add the iOS and Android platforms.

Run the following commands to add the iOS and Android platforms

ionic platform add ios

ionic platform add android

Add the Geolocation Plugin

As I just mentioned, we will be included the Geolocation plugin for grabbing the users current location. This will enable us, if we wish, to use the devices GPS to grab a more accurate representation of their location.

We will be using the ngCordova version of this plugin, so let’s set ngCordova up before we add the plugin.

NOTE: It’s completely possible to use this plugin without ngCordova, but ngCordova makes the plugin easier to use.

Run the following command to include the ngCordova library

bower install ngCordova

Add the ngCordova library to your index.html file

    <script src="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>

Require ngCordova in the angular module in app.js

angular.module('starter', ['ionic', 'ngCordova'])

ngCordova should now be installed and ready to use in our application. Next, let’s install the Geolocation plugin.

Run the following command to add the Geolocation plugin

cordova plugin add cordova-plugin-geolocation

NOTE: If you are using PhoneGap Build go here for instructions on adding the plugin to your project.

Include the Google Maps JavaScript SDK

Now we need to include the Google Maps JavaScript SDK in our app. This service must always be inlcuded remotely, and you will need to set up an API key through the Google Developers Console if you don’t want limits set on the amount of calls you can make to the API. You can find instructions on how to do that here.

It does cost to use the Google Maps API, but the free tier is extremely generous:

“If your site or application generates 25 000 map loads or more each day, for more than 90 consecutive days, we’ll get in touch with you to talk about payment. Don’t worry, if you go over the limits, we won’t immediately shut off your API access or display error messages on your site.”

so unless you’ve got a serious amount of users on your app you won’t hit the limit. Let’s get the SDK set up now.

Add the following script to your index.html file

    <script src="js/app.js"></script>
    <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY_GOES_HERE&sensor=true"></script>

Make sure you put your API Key in the URL above, or just drop the key parameter altogether.

Create a Map in Your Application

Now we’re going to look at how to actually display a map in our Ionic application. To do that we will be creating a new view with it’s own template.

Create a new templates folder at www/templates

Create a new file called map.html in the templates folder and add the following code

<ion-view>
    <ion-content>
        <div id="map" data-tap-disabled="true"></div>
    </ion-content>
</ion-view>

To use <ion-view> we are going to need to modify our index.html to include the <ion-nav-view> directive. This acts as a placeholder where we can switch between different templates we create.

Modify the <body> section in your index.html file to reflect the following:

  <body ng-app="starter">
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Maps</h1>
      </ion-header-bar>
      <ion-nav-view></ion-nav-view>
    </ion-pane>
  </body>

The other piece of the puzzle for switching between views is to set up routing.

Add the following config to your module in app.js

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('map', {
    url: '/',
    templateUrl: 'templates/map.html',
    controller: 'MapCtrl'
  });

  $urlRouterProvider.otherwise("/");

})

Since we only have one template, we’ve set it up as the default and have also assigned it a controller of MapCtrl which we will create now. This controller will be responsible for initialising a new Google Map.

Add the following controller to your app.js file:

.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {

});

Notice that I have injected the $cordovaGelocation service into this controller – this is a service for the Geolocation plugin we added that is supplied by ngCordova. We will be making use of that now to grab the users current position, and then initialise a new map which will be centered on the users current position.

Add the following code to your new MapCtrl controller in app.js

.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {
  var options = {timeout: 10000, enableHighAccuracy: true};

  $cordovaGeolocation.getCurrentPosition(options).then(function(position){

    var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);

  }, function(error){
    console.log("Could not get location");
  });
});

If you run your code using ionic serve now you will notice that we can’t actually see the map yet. That’s because there’s a couple of CSS changes required for it to display properly.

Add the following rules to your scss/ionic.app.scss file

.scroll {
    height: 100%;
}

#map {
    width: 100%;
    height: 100%;
}

Now you should see a map centered on your current location (depending on your privacy settings of course):

Ionic Google Maps Example

Add a Marker and Info Window to Your Map

Just a map by itself isn’t exactly very exciting, so let’s look at how to add a marker to the map.

Add the following code to your MapCtrl controller, just after you initialise the map

    //Wait until the map is loaded
    google.maps.event.addListenerOnce($scope.map, 'idle', function(){

      var marker = new google.maps.Marker({
          map: $scope.map,
          animation: google.maps.Animation.DROP,
          position: latLng
      });      

    });

After the map loads, we’re creating a marker with the same position that we used to center the map, so you should see a marker drop right where you are now.

Finally, we might also want to add a pop up window when a user taps the marker to give them a little more information.

Modify the code in MapCtrl to reflect the following

    //Wait until the map is loaded
    google.maps.event.addListenerOnce($scope.map, 'idle', function(){

      var marker = new google.maps.Marker({
          map: $scope.map,
          animation: google.maps.Animation.DROP,
          position: latLng
      });      

      var infoWindow = new google.maps.InfoWindow({
          content: "Here I am!"
      });

      google.maps.event.addListener(marker, 'click', function () {
          infoWindow.open($scope.map, marker);
      });

    });

Now if you tap the marker you should get a little pop up saying “Here I am!”.

BONUS CONTENT: Grab the complete source code for this lesson by entering your email address below:

As you can see it’s reasonably easy to get a simple Google Maps integration set up in Ionic, and if you just want to manually load a few markers onto a map this will work well for you. There’s a few problems that arise when you start getting a little more in depth though, like:

  • Loading markers dynamically from a database
  • Loading lots of markers (you don’t want to render thousands of markers onto a map at the same time)
  • Dealing with users without Internet connectivity – we’re loading the Google Maps SDK remotely so our apps going to throw some errors if it can’t be loaded

I’ll be releasing tutorials in the not too distant future on how to deal with all of these issues so stay tuned and leave any questions or comments you have below.

UPDATE: I’ve added a new tutorial about dynamically loading markers with Ionic and Google Maps which you can check out here.