Ionic Google Maps Example

Part 1: Integrating Google Maps with an Ionic 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.

  • Pingback: Installing ngCordova in an Ionic Application | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Pingback: Part 1: Using the $http Service in Ionic to Dynamically Load Google Map Markers | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Pingback: 170 Ionic Framework Resources()

  • Pingback: Monitoring Online and Offline States in an Ionic Application | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Mark

    Do you have the source code in github or other site?

  • Pingback: Part 3: Advanced Google Maps Integration with Ionic and Remote Data | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • great post thanks,
    is it possible to show us how to add a watch to the current geoposition, to update the position when you walk, and to rotate the screen (like google maps does) in your walk direction, and to keep the screen on and preventing it from getting off.
    that would be great if you add these features to this Post or make a new Post.
    isaid

  • Francesco

    Stupid question: The map works perfectly in the browser and does not even open on the phone or on emulator.
    When i set up the Google Map API i have selected: Google Maps JavaScript API
    Then i have generated a Browser Key.

    I have choosen the correct API?
    Which kind of key i have to select?

    Thank you!!

    • Browser key should be fine, also make sure that you are whitelisting the Google URLs in your config.xml. Sorry for the late response!

    • Giann Godoy

      hi, i am brazilian and i had the same problem, realized that in map directive the code responsible for its creation was inside the function to search the user’s location, ie, the map is run on the device only when the gps is enabled, to fix the problem place the map to start first and the function to get location after 😀

  • jatin

    very good post

  • CityLims

    While this approach will work, the performance will be terrible on mobile if you anticipate any scrolling around on the map, or refreshing markers, etc. When building a hybrid mobile app, you shouldn’t just build a web app. You’re much better off using the cordova google maps plugin (which provides the native map), or a different api like leaflet.

  • Fernando Montesinos

    I’m trying to display this tutorial inside a tab, the thing is, it’s not displaying the map. Can anyone take a look into my code?

  • Pingback: Ionic 2: How to Use Google Maps & Geolocation | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Angelo Rigo

    Thank´s Josh for this great tutorial! just try and it is up and running. There is a way to get the actual detected city? in order to populate a select box with that city ? so the city id will be used into a sql query ?

    • Try looking into the Places API: https://developers.google.com/places/javascript/ I’ve never used Places to turn coordinates into the nearest city, but I’m sure it’s possible. I have set up an autocomplete list before that suggests locations that are closest to the user, i.e if I started typing ‘Ad…’ Adelaide would pop up.

  • ShaneN

    Hi Josh, I’m getting stuck on the part after you update the css and test to see if the map is showing. I followed it step by step but when I ionic serve, noting shows up in the browser. Any ideas of where I might have gone wrong ?

  • Craig Ward

    Thanks heaps for the tutorial. I’ve got the app working fine in a browser via ionic serve but in the ios emulator (iPhone 6, 9.1) I just get a blank page in the app. I do get prompted to confirm it wants to know my location though. Any ideas how to troubleshoot? I’ve tried deleting the app from the emulator and multiple builds/emulates.

  • Victor Kurauchi

    thanks man ! it was really simple and helpful you explanation.

  • Niklas

    hello

    Nice tutorials, i have follow this 3 times…
    All i get is : Could not get location

    Witch API key do i need to use, I have try browser, android

    I´m working in ionic.

    • Trung Pham Quang

      Make sure that you have following permissions in your AndroidManifest file:

      Don’t forget to enable location on your mobile

      • Niklas

        Now i have done Everything again,
        I can´t see the map…only blank page.
        I have used browser key and Android key and nothing happends…
        The error ” Could not get location ” is gone.

      • MasterP

        I have the same issue as Niklas, does anybody can debug us?

      • JoseP

        Same problem here. Someone have an idea?

      • akash kabra

        just change the map.html
        with below code

        dont keep any tag. only yhose 5 lines in map.html

        it should work .

      • Kingsley Simon

        @disqus_sJxjm3xnBG:disqus @joshmorony:disqus @MasterP. anyone solved this? im stuck at white screen too.

  • Atula Guleria

    hey Josh !
    stucked at css point. only see a blank page.
    plz guide.

    • Matt

      I was getting the blank page after doing the tutorial. It turned out that I had not setup sass for the project (I was reusing an existing testing project I have). So go ahead and run: ionic setup sass.

      My understanding is that if you are not using sass, then the change to this file: scss/ionic.app.scss will be ignored – hence the css required to show the map does not get changed.

      I could be wrong, but it worked for me!

      Also, if you’re got the white-list thing installed, you’ll likely have to configure a bunch of CSP rules at the top of your index.html file!

      Cheers,

      Matt.

      • Atula

        Thanx for replying
        & problem is now resolved.

      • Rob

        Unfortunately this don’t solve my blank page :/

  • Jessica Thompson

    Hi,

    I am wanting to include geolocation so that it will track where the user is and to provide them with nearby health services and give them directions of how to get there.

    can this be done?

    please help

  • Would you be able to guide on working with google mobile sdk. it is soo hard getting it up and running…

  • stevexm

    Hi Josh, g’day and thanks for a great tutorial. Quick question: whether Apple will accept an app that loads ‘remote’ code, namely the google maps sdk? I thought no, they will not?

    • Yes they will accept it, I’ve had multiple applications accepted with the Google Maps JavaScript SDK. They only reject applications that try to download binary / executable code, or applications that automatically update themselves in a way that fundamentally changes the behaviour of the app.

      • stevexm

        Thanks, I am very much appreciative for your clarification how external sdks (like Google maps) can be incorporated into an iOS app!

      • Nicola Sanitate

        Can you list your apps with Google Maps JavaScript SDK published on Apple Store?

  • There should be tutorial like this one for google map mobile sdk… It is so hard getting up adn running with mobile sdk.

    performance is huge difference and features compare to javascript api sdk

  • Johannes Peter

    Hi, thanks for this great tutorial! But i´m in dire need of help. I cannot display the map! I checked the code and started all over like 5 times, still getting this error and i´m pretty sure it has to do with the way i include the map or the API Key – still i cannot find a solution. I tried 2 ways to include the google maps api in the index.html:

    1. As in the tutorial

    Error JavaScript Console: Google Maps API warning: SensorNotRequired (i tried to set sensor=false) in util.js:22

    2. The way google recommends on its developer site:

    Error JavaScript Console: Uncaught InvalidValueError: initMap is not a function in js?key=MY_API_KEY&callback=initMap:92

    Any help?

  • gugasevero

    Nice tutorial. Everything works fine.

  • Kingsley Simon

    this just diaplays a blank screen.

  • Alejandro Planter

    Thanks Josh, everything’s working fine, just got a little problem, look at this code:

    .scroll {
    height:35%;
    }

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

    So i scaled the map view to 35%, it’s working on iOS, but on Android keeps displaying at 100% (at least on Lab View), what should I do to fix this?

    • Rofi

      hello, this doesn’t work on my android device. any advice sir? thx

  • Key Cobo

    Hi, I have a problem, the map don’t show, and i don’t know what I do :s, I need help with that please. tranks

    • Michael Merletti

      if you run it in a browser make sure localisation is enable

      • Key Cobo

        thank you. i can resolved that :), now my problem is other :(, that don’t is referent to this post, is refrent to the read and write the data of a csv, yo can help me?, please

  • Michael Merletti

    hi josh, good job, I just have a little problem the event “click” not working…

  • sandeep kumar

    Hi ,

    I am getting empty page even after doing the above changes

    here are my files

    index.html — http://pastebin.com/qWaQM4V3

    App.js — http://pastebin.com/BDcLXTfQ

    Controller.js — http://pastebin.com/igpDwp9B

    locate.html — http://pastebin.com/H5FQ3uw2

    ionic.app.scss — http://pastebin.com/BT6Zi6aa

    could you please help me on this issue

  • vagostep

    Great.! I have one question.

    In this map I can make a route between two markers ?

  • Ana

    If you got a blank page…you have to put the css code into www/css/style.css. That’s all!! Thanks for the great job

  • prasad

    hi josh, Google map loaded at once, then i went back and came to same page, map is not getting loaded in browser, in my ios mobile coming blank page..

  • Chirag thaker

    Very good tutorial, thank you

  • Raúl Hernández Caballero

    Hello, great post. I am having problems with GPS detection over Google Maps in Ionic App. When I start the App with GPS off and later I change from Settings device to GPS on, the GPS detection is not working. The function responses always GPS Timeout! ERROR = 3. is there any solution? thanks

  • Thanks guys, it works

  • vaggelis

    hello josh, i had setup sass and added the rules to the css file.i have made a map templete in my app and when i try to navigate to it it does nothing.however the url of the template has been changed from http://localhost:8100/#/app/home to http://localhost:8100/#/app/map and when i refresh then i get the blank page.what goes wrong? thanks in advance!

  • JohnDBP

    Hello everyone, I have a question regarding maps. At the time one publishes the app, is there anything else that has to be done in order for the map to show? Im getting a blank page in the map place.

  • jenvigo

    If you only see a blank page, make sure you have css well linked in your index.html. It worked for me. 😉

  • Cesar Omar El Wasa

    awesome, master!

  • Cesar Omar El Wasa

    It works good on browser and my android, but it doesn’t works on android emulator :S
    $cordovaGeolocation.getCurrentPosition returns a timeout error
    i increased the timeout but still not working
    var options = {timeout: 20000, enableHighAccuracy: true,maximumAge: 0 };

  • Cutty Bang

    I’m surprised that more people haven’t noticed the addEventListenerOnce error that’s built into this tutorial.

  • Syahmi Nawi

    Hello, nice tutorial and it works smoothly but i encounter 1 problem, if user start the app without internet connection and then reconnect to internet and recall the map function it will give an error ionic.bundle.js:20434 ReferenceError: google is not defined at $cordovaGeolocation.getCurrentPosition.then.$ionicPopup.alert.title (map.js:17)

    cant recall the map function if user accidentally ran the program without internet.

  • Lucas Schwantes

    Great tutorial! Thank you so much

  • Hi Josh!
    Thank you again for this tutorial. Its a great jumpstart for many usefull apps.
    If you can please make this tutorial by using https://github.com/mapsplugin/cordova-plugin-googlemaps
    Native Google Maps plugin. It will be very performance emprovement.

    Thank you again
    Regards!

  • Mohamed Boufraine

    I post some errors that I had with their solutions:

    1/ If you have this warning in your console’s browser:

    “maps.google.com/maps-api-v3/api/js/26/14/intl/fr_ALL/util.js:210 Google Maps API warning: SensorNotRequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required“.
    You just must remove the “&sensor=true” at the end of the script:

    so, now you should have:

    2/ If you have this error in your console’s browser and you’re using ionic:

    ng-cordova.js:3559 getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.getCurrentPosition @ ng-cordova.js:3559 app.js:64 Could not get location

    open your console and type : > ionic address
    and select “localhost”

    3/ And finally if you have a blank page, just type “setup sass” in your console

  • Bourgeois Guillaume

    Excellent ! Thank you for your work

  • I got error;

    TypeError: Cannot read property ‘firstChild’ of null

    Before this it works but now it gave me error. https://uploads.disquscdn.com/images/71b5048e9b861f43777c2c749d243a8496b0f5e2cacc7032122bf77fc53ac1c0.png

  • Neny

    Thank you for this tutorial. Small problem: no marker on a map. I read all comments. I am only one with this problem. Any idea?

  • josh moron

    fuck you and your web joshMORONy

  • Captain Cap’n

    for people who’s stuck at the scss step: just copy it to the ionic.app.css

  • eleh

    hi Josh MORONy, your tutorial sucks, doesn’t help at all, rot in hell.

  • lalal

    test

  • Shane

    I’m trying to compare my mapCtrl to yours to overcome an issue. but the source code isn’t coming to my email. Please help.