I already wrote an article covering Google maps: Using Google Maps With Ionic Framework, unfortunately, I forgot to write a most important part, how to use Google Maps with Cordova Geolocation plugin. This topic is going to be a point of this article.
 
Unlike my previous articles covering various Cordova plugins, this one will feature two plugins. Changes made to Cordova 4.0 + made it necessary to use Whitelist plugin for every application that requires external resources (Google Maps API).
 
Update: 14.01.2016 - Example was updated to match latest Ionic v1 changes
 
I’m writing this article to show you how easy it is to do just that.
 
 

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)
 

Preparation

 
Before we can start make sure you have everything configured correctly.
 
You will need to have these:
 
  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
In case you don’t have a properly configured development environment take a look at this article: Ionic Framework | Installation Guide.

1. Update Ionic & Cordova

 
Don’t forget to update Ionic and Cordova, older versions may not work with this tutorial:
 
npm update -g cordova ionic
 
If you can’t update them to latest version make sure you have the last NodeJS installation.
 

2. Create a New Project

 
ionic start IonicGeolocationDemo blank
cd IonicGeolocationDemo
 
Warning: Since a few of my readers never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.
 
Now we need to include an appropriate mobile platform; we’re going to add Android platform:
 
ionic platform add android
 
if you’re using MacOS, you can also add an iOS platform:
ionic platform add ios
 

3. Download ngCordova archive

 
ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way.
 
Download ngCordova zip file, here’s site link:
 
Official Site Docs Download Link
 
 
Unzip this archive and find a file named: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.
 
Open your newly created project directory and copy ng-cordova.min.js to this location: IonicGeolocationDemo\www\js.
 
Now include this location to index.html located at IonicGeolocationDemo\www; add it above cordova.js file, like this:
 
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
 

4. Install Cordova Geolocation and Whitelist Plugin

 
Next line will import and install necessary plugins into newly created project:
 
cordova plugin add cordova-plugin-geolocation
cordova plugin add cordova-plugin-whitelist
 
GitHub - Geolocation GitHub - Whitelist
 
 

5. Possible error solution

 
If you receive this error:
 
ERROR 2: application does not have sufficient geolocation permissions
 
You can solve it by adding appropriate permissions. On Android platform, open your project, search for AndroidManifest.xml and add these lines:
 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
 
Funny thing, this same example is working just fine with Ionic 2 without these permissions.
 

Development

 
At this point, you should have everything set up and ready, we can start working on our example.
 
Go to IonicGeolocationDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:
 
var app = angular.module('starter', ['ionic', 'ngCordova'])
 
Open index.html file, add a controller to ion-content directive:
 
  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content ng-controller="MapController">
      </ion-content>
    </ion-pane>
 
Initialize this controller in app.js file; don’t forget to inject $cordovaGeolocation service, like this:
 
app.controller('MapController', function($scope, $cordovaGeolocation) {

});
 
We have included whitelist plugin several steps ago, now we need to initialize it properly. Add this meta tag to index.html HEAD content:
 
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
 
If you have a previous Whitelist plugin experience, you may notice that this tag differs from the one mentioned in a plugin official documentation. Regrettably, the original meta tag is not usable with Google Maps API, so I reverse engineered this one to work.
 
It is also important to wrap geolocation code into Ionic deviceready event, execution will timeout without it:
 
app.controller('MapController', function($scope, $cordovaGeolocation, $ionicLoading) {
    
    ionic.Platform.ready(function(){
        // Code goes here
    }				
});
 
Everything else will be reused from the previously mentioned article.
 
Continue Reading

  • Dinakaran Rahman

    Hi, No matter how much I try, I see only an empty page. I tried both ionic CLI and visual studio 2015. Still no use. Is this the entire set of code or do we have downloadable demo ?

    • If you wish I can mail you this demo project? I can also tell you my Ionic CLI/Cordova version.

      • Dinakaran Rahman

        That would be a great help for a starter like me. my email id is dinakaran.rahman@gmail.com

      • Dinakaran Rahman

        Hi Dragan,
        I am waiting for your reply.

        • Project sent

          • Dinakaran Rahman

            Thanks a lot. Let me try

          • Dinakaran Rahman

            Actually I still see an empty screen. My
            Ionic version: 1.6.3
            Cordova Version: 5.1.1.
            Should I have to downgrade to 1.6.1 ?

          • Dinakaran Rahman

            even in my device I see till the toast “acquiring location” then blank

          • Most important question, have you turned internet connection on? This example requires external resources.

          • Dinakaran Rahman

            Yes. I surely did, in both my laptop and android tablet. In laptop I used “ionic serve” to start and in tablet I installed the apk after build. It still comes as blank only with the header bar

          • Have you used Chrome remote debugging tool?

    • Have you downloaded source from my GitHub repo? What platform?

  • If you wish I can mail you this demo project? I will also include Ionic CLI/Cordova version.

  • Fredrik Søgaard

    Hi, I can get this to work in the browser, but iOS emulator and iOS device doesn’t work. I get an

    PositionError
    code: 2
    message: “The operation couldn’t be completed. (kCLErrorDomain error 0.)”

    Maybe it has something todo with the whitelist? I have added the recommened by you meta tag.

  • Owltastic

    Hi – I’ve followed all of your directions, and I still cannot get the google map with geolocation to work when I ionic serve –lab. Cannot figure out what I’m doing wrong =(

  • This error tells you that mobile device or emulator can’t connect to Internet.

  • Hi Bro, Awesome tutorial.. But the thing is maps show in only half of the screen.. (column-wise). The remaining half is blank. Any idea on how to fix this.. ?

    • Hm, map should cover your whole available content. Where are you testing this application? Browser, Ionic view, emulator or a real device?

      • Hi Dragan, I got this fixed. I had given few style properties for the .scroll class in my css. This created conflicts when I used this div inside . Using the div outside did the trick. Thanks.

        I would like to make a small suggestion. Please add a small note about the css stuff you need to add to make this work.
        #map {
        height: 100%;
        width: 100%;
        }

        (I also learnt how to remotely debug using chrome today.. 🙂 Thanks again. )

  • willywg

    I also see a blank page. But solve with this css:

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

    .scroll {
    height: 100%;
    }

    • Thanks, I will update my example according to this CSS.

  • willywg

    Hi Dragan, thanks for this awesome tutorial.

    Maybe you can add this for test the app on any browser:

    if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
    document.addEventListener(“deviceready”, onDeviceReady, false);
    } else {
    onDeviceReady();
    }

    Because the deviceready listener only success on a mobile device.

    • Thanks for this info, I’ll do it a little bit different. I will use Ionic ready event which works precisely as you described. Unfortunately, I need to wait two more days, this project is on my other computer and I can’t access it right now.

  • hi,

    some poeple say that they get a white page istead of desplaying the map , i had the same issue and it got it working after i removed the part of: document.addEventListener(“deviceready”,…. this ist not supported for ionic from ngcordova any more, instead you have to write a $cordovaPlugin.someFunction().then(success, error); in the $ionicPlatform.ready(function().

    but i would like to ask, how can you get the map updated for my next position if i move with the device, i use $cordovaGeolocation.watchPosition but it is not working.

    thanks

    • Is this not working while your application is in the background or still active?

      • still active, after a while the screen want to get down but i activate it with my finger, so the app is active

  • Luís Cunha

    Hi,

    The article’s title mentions geolocation functionalities with cordova, but when I run the app I just see an empty google maps screen. Am I missing something?

    • If you have downloaded my GitHub example you still need to do everything mentioned in this tutorial. That code is missing plugins and mobile platform.

      • Luís Cunha

        I didn’t download the github example, I followed the tutorial, so I have what the article describes. But I’m getting a strange error in the chrome console:

        GET http://localhost:8383/IonicGeolocation/lib/cordova_plugins.js net::ERR_EMPTY_RESPONSE

        It seems as if it’s not being able to compile the cordova_plugins.js and is just opening a google maps screen. What could be the problem?

        • Why don’t you zip your project and mail it to me? On the other hand, you may not be able to mail it because of its size, maybe Google Drive or Dropbox?

          • OK, from what I can see your code is working just fine. Except your missing Ionic Keyboard plugin, which is, by default, available in Ionic CLI since last few months (error is thrown, but the application works just fine). Tell me your Ionic version and Cordova? (type: ionic –version and cordova –version). Next what platform are you using? I’m currently doing this with Android. Here’s a fully built project: https://drive.google.com/file/d/0B64wvO1oGlx-RkJ1N2lxdWpFQlk/view?usp=sharing

          • Luís Cunha

            That fully built project works perfectly thanks, still getting the keyboard thing though.

            C:UsersLuis>ionic -v
            1.6.4
            C:UsersLuis>cordova –v
            5.2.0

            But it’s working fine on my android, so it’s fine.

          • I’m glad to be of help. I think your original problem was related to initially installed plugins. You unintentionally fixed your problem by removing them. It doesn’t matter now, it works.

          • Luís Cunha

            I’m interested in using ionic to build a geolocation/gps style app for tourism, with dynamic marker drawing, route calculations, etc., would you happen to know of a tutorial to get me started on something of this sort?

          • If you can tell me specifics I can write you one, somewhere during next week?

          • Luís Cunha

            I have already written a native java app for android that draws routes from the user’s position to the selected marker position and place the zoom and camera position to fit both points, calculates which points of interest are nearby to display them on screen and allows for address search using google places. I’m looking for information on how to do the same things, but with a hybrid app so I can put it on iphone/windows phone, and ionic seemed the best one.

          • Ok, I’ll write something similar and we’ll work on top of that. This could be interesting to my other readers.

          • Luís Cunha

            Alright then, looking forward to it.

  • I followed the tutorial but on Android 5.1.1 with location services enabled I’m seeing a:

    code: 2
    message: “application does not have sufficient geolocation permissions.”
    __proto__: PositionError
    PERMISSION_DENIED: 1
    POSITION_UNAVAILABLE: 2
    TIMEOUT: 3

    This indicates to me that ngCordova is working but isn’t allowed to access location services.

    The application, though, doesn’t appear in the recently accessed list in the settings->location (I guess this is sort of sensible, given that it didn’t successfully attempt to).

    I wonder how to fix this?

    • Seems that you need to put the required configurations in the relevant XML files (yeah, answering myself).

      See: http://cordova.apache.org/docs/en/2.5.0/cordova_geolocation_geolocation.md.html

      • What you’re reading is old Cordova documentation. This is a new one: https://www.npmjs.com/package/cordova-plugin-geolocation. If you’re using ngCordova then you don’t need to touch config.xml or AndroidManifest.xml, everything should be configured automatically. Though, you should, of course, check everything.

        • For example, here’s a version I built few days ago for someone else: https://drive.google.com/file/d/0B64wvO1oGlx-RkJ1N2lxdWpFQlk/view?usp=sharing

          • It’s a Nexus 4; Google Maps and other things can find location.

            I just ran the code you passed in and got a time out – I think I hit another bug.

          • I think this is related to your Cordova environment. This code was tested and used in numerous occasions. If you can, download previously provided code and try to deploy it.

          • I downloaded the “rar” file from https://drive.google.com/file/d/0B64wvO1oGlx-RkJ1N2lxdWpFQlk/view?usp=sharing.

            I ran it using “ionic serve -w chrome” just to prove it worked; asked me to allow location in the browser (and for some reason seems to only find the nearest capital city center but that’s beside the point).

            Ran “ionic run android” and got:


            code: 3
            message: “Timeout expired”

            $ cordova –version && ionic –version
            5.1.1
            1.6.4

            I didn’t need to manually run bower, composer or npm to perform the above test.

            Settings how that the application has permissions to access the location service. Google Maps is able to find me fine.

          • Try using a higher timeout value:

            timeout: 20000

          • Oops, my editing has muddled the replies – basically you were right; I’d gotten my Cordova environment thoroughly muddled but it is working and thanks for your quick and insightful responses.

          • I’m always here to help my readers. Come back if you require more information and subscribe if you want to receive more information about Ionic. We’re sending newsletters once every 1-2 weeks, no point in been spammy.

  • Jomabell Lascano

    i can’t install the plugins :/ why?

    • How would I know? Why don’t you post an error log?

  • Mattheus

    What you think about to update the tutorial in the follow snippet:

    app.controller(‘MapController’, function($scope, $cordovaGeolocation, $ionicLoading) {

    document.addEventListener(“deviceready”, onDeviceReady, false);
    function onDeviceReady() {

    // Code goes here

    }
    });

    To:

    app.controller(‘MapController’, function($scope, $ionicPlatform, $cordovaGeolocation, $ionicLoading) {

    $ionicPlatform.ready(function() {

    });

    });

  • Raghu A

    Thanks for great post on how to integrate the geoLocation in an IONIC app. I found that using only getCurrentLocation was not giving a reliable result, so have written a service based on watchPosition. Details at http://hp2ra.blogspot.in/2015/10/reliable-way-to-get-current-location.html

    • Thank you, someone will find your post very useful. 🙂

  • Ömür Bilgili

    Please update this article for new visitors. Because “document.addEventListener(“deviceready”, onDeviceReady, false);” not working anymore. Change it with “$ionicPlatform.ready(onDeviceReady);” and adding $ionicPlatform parameter to controller function.

    • Thank you, I’ll do it over the weekend.

      • Enrique del Bosque

        You should really update this issue.

        Anyway, great job… thanx for the tutorials man…

    • James

      Thank you! It’s frustrating how much inaccurate and out-of-date ‘instruction’ exists for Ionic. Hopefully Dragan gets around to updating this article so it will actually work.

    • Enrique del Bosque

      Thanx mate!

  • Anderson Juhasc

    The map is not showing up, is blank.

    • Have you installed a whitelist plugin? It will not work without it. Plus you also need a provided security meta tag. Also if you’re not sure what’s happening take a look at a console log, your error will be there, but I’m sure it’s related to whitelist plugin.

      • My console is not showing any errors. Getting the location succeeds, showing the map does not.

        – Never mind. Problem was css: I used an existing style.css which had the height/width at 100% for ‘map’. For the HTML you use, this should be for ‘#map’. Now the map is shown! 🙂

  • lol

    Followed everything, the map didn’t showed up.
    Then using the HTML5 geolocation(navigator.geolocation) + Google Maps API (pure js without Angular) instead of your method ($cordovaGeolocation), it works well. Not sure what problem is it.
    Also, need to add the cordova geolocation plugin for adding the location service permission.

  • Harry Wang

    get location fail at first. but i changed timeout from 2000 to 5000. it works fine. lol

  • azob

    I have the same problem: TypeError: Cannot read property ‘offsetWidth’ of null

  • RAMDdFLEET

    How to Calculate directions between multiple locations?

    • Google this topic, it’s frequently asked question.

  • Lucas Cardoso de Araujo

    Hello, I am getting this error:
    PositionError {
    message: “Timeout expired”,
    code: 3,
    PERMISSION_DENIED: 1,
    POSITION_UNAVAILABLE: 2,
    TIMEOUT: 3
    }
    if you can help me, I am very grateful

    • Error is telling you everything you need to know, just use a longer timeout.

  • santhosh h

    Good Example to learn, I am getting this error:
    code: 2,
    message:application does not have sufficient geolocation permissions.
    }

    i was not going for map i just want to know the location.but i’m getting this error why it is so?
    what shouls i change for android phone to have permission.i was not working on emulator. i tried to work my smart phone only

    • Kote Ujmajuridze

      I have same error. Did you solve this?

      • I found a solution. If you’re working on a Android platform, add these lines into AndroidManifest.xml file:

        • Martino Perez (Cipsicko)

          Hi, i’ve the same problem (code:2 , message: application does no have sufficient geolocation permission)
          in fact when i try to install the apk i don see the requested permissions in recap view. So i added the three line that you suggest, but nothing changed.
          now im using the native html5 geolocalization with these options
          timeout: 31000, enableHighAccuracy: true, maximumAge: 90000
          if a run from ionic run android (real device) all is workign correctly, but if i build the apk (from ionic package tool), the problem appears.
          any solution?
          many thanks

  • Nirdesh Pathak

    Hello,
    Good Example to learn, I am getting this error:
    even in my device I see the message “acquiring location” then blank

    • Try using a longer timeout.

      • Nirdesh Pathak

        Thanx, Now its working

  • Guru Prasad

    Hi,

    Nice article. I am trying to adopt this solution in an app. However I get an error “Unknown provider: $cordovaGeolocationProvider <- $cordovaGeolocation"

    Any tips how this can be resolved?

    • This error usually means ngCordova is missing or not properly configured. Check it out.

      • Guru Prasad

        Cool, got it working 🙂

  • Tom Disheroon

    Hey, great tut with lots of great parts to use in various projects. Issue current is one similar to Nirdesh from a few days ago:

    In ionic serve timeout behaves as expected, but after ‘Acquiring Location!’ goes blank

    When pushing to Nexus 7 android, regardless of timeout, ‘Acquiring Location!’ stays on screen.

    I have used various timeouts from 90-50000.
    Greatest ( :-/ ) thing is there is NO error in either the console or server log. Web Inspector also has nothing to say.

    Any help is appreciated.
    Cheers

  • ncubicx cf

    Hey, nice tutorial, but will it update our position as we move? or does it show the location of where the app started?

    • This is just a tutorial made to show you how to combine Google Maps with Ionic. Your question is more related to Gogole Maps V3 API. Just google it, you’ll find more then enough working examples you can combine with a code provided in this article.

  • Very good! this tutorial I loved, but is necessary the update. look this

    Ömür Bilgili • 3 months ago

    Please update this article for new visitors. Because “document.addEventListener(“deviceready”, onDeviceReady, false);” not working anymore. Change it with “$ionicPlatform.ready(onDeviceReady);” and adding $ionicPlatform parameter to controller function.

    After changes it worked

    Thank Drangan …… 😀

  • Arul Frances

    Great Article! Your Special mention on the Whitelist helped a lot!
    And from my experience on the Whitelisting behaviour is because of not updating the version of Cordova and Ionic. And installation of Whitelist! 🙂

  • hasan r

    it works on Ionic Lab, but when I tried in Android Device, the maps is not showing 🙁
    please help

    • hasan r

      oh never mind, I add whitelist in my config.xml file

      thanks for writing a great article!!

      • …. or that 😀 and thank you 🙂

      • Preetham Rai

        can you please tell me how to add whitelist in .xml file?

    • Just use a longer timeout, it should do it.

  • Nirdesh Pathak

    Hi, nice tutorial, Please tell me how to add multiple marker in this.

    • Just google “Add multiple markers to Google Maps V3 map”. My example is using standard Google Maps API, you can reuse it with any tutorial you can find.

  • Priyanka Nayak

    Fantastic blog..Definitely worth reading and trying hands on 🙂 This helped me developing my first ever mapping app.

  • Jeffrey

    Its working fine in browser but not working on my android phone. Any solution for this issue?

    • Preetham Rai

      I am facing the same problem, Its working in mobile browser but not as app. Even tried increasing timeout and white-listing objects. Any solution here?

      • ahayder

        same problem here, any solution?

      • Diluk Angelo

        Try this
        var posOptions = {timeout: 20000, enableHighAccuracy: true, maximumAge: 10000 };

  • Anand H

    Thank you for the wonderful article, helped me write my first functional mobile app 🙂

    Struggled quite a bit even after copy pasting the js code to get it working, got it working after adding a ‘); ‘ on the second last line.

    Thank you.

  • Alex Ilies

    Hello. Thank you very much for this tutorial. I have a problem. The app run well on Chrome browser and on android simulator but the map is not loaded in Safari or iOS Simulator(also on real device). The app.js controller return an error(‘position error”) when I do debuging in Safari. Only HTML header is loaded. Could you help me with a hint, please?

  • CeebLaj Thoj

    Thank you for your article it working well in computer browser but on real devices I’ve got a blank screen the map is not showing, please help me to what’s going.

  • Diluk Angelo

    does this update realtime ?

    • shivkrishna shah

      yes

  • BB

    Timeout expired on device Android. I tried to increase timeout to 50000 and I still have the same problem.

    • Caro Lopez

      Do you have a solution?

  • shivkrishna shah

    i am waiting eagrly

  • shivkrishna shah

    hey how to add marker on location/map
    🙂

  • shivkrishna shah

    very useful app N article as well

  • Caro Lopez

    Code 3 – timeout expired
    Can u help me?

  • Olatunji Gabriel

    very useful tutorial but it is just spinnig, diplays acquiring location can anyone help me out?

    • Yacobus Sandi

      same problem here, please help

  • Sayon Adhikary

    Amazing blog! Thanks!

  • Anandh

    Superb, Very nice article

  • Ranvir Gorai

    it is working fine in browser using ionic serve but not working on actual device ios and Android.
    so please tell me the solution.

  • kamesh

    Hi ,
    its working fine in browser, but not working on android device.

  • Great Tutorial. Thank you very much. I had to install the cordova-plugin-geolocation for access on phone. And change the code a little bit to add the class ‘show-map’ to the map container.

    let mapDiv = document.getElementById(“map”);
    this.map = new google.maps.Map(mapDiv, mapOptions);
    mapDiv.classList.add(‘show-map’);

  • Joko Auditis Bisnisbatam

    thank u, its working fine…. error.message =”timeout expired” do not come again :*

  • Francesco Mussi

    Same for me. Works good in the browser but on device I get a blank page.
    (the demo has been download from github)
    These are the errors in the console:

    https://uploads.disquscdn.com/images/4d27c03efdcc19b6844bb5fcade75ef6abf6858ae213bfebe9e12f5c1e896e88.png

  • Jhon Sidjwk

    WARN: ionic.project has been renamed to ionic.config.json, please rename it.
    message received while running app from github on 2016-09-28

  • Carlos

    Hi, Gajotres.
    I’ve downloaded your code from GitHub, renamed ionic.project to ionic.config.json (as mentioned by Jhon Sidjwk below) and installed it in my iPhone 6 (iOS 10). The result is a blank page with the header “Map example”.
    Please, can you confirm that?
    Thank you.

  • Nice

  • themilossh

    Hello, my code is wrapped in ionic.Platform.ready(function(){ }); Now,
    before wrapping it inside it, everything worked well(both geolocation
    and google maps) on my app when testing using browser or newer phone,
    like Samsung S7, but when I was to try it in an emulator defaulting
    emulating device to Nexus 5, I was getting Timeout error. To fix that, I
    followed instructions from within this post, and ever since I used
    ionic.Platform.ready(function(){, I’m getting following error: Error in
    Success callbackId: Geolocation166915056 : TypeError: Failed to execute
    ‘getCurrentPosition’ on ‘Geolocation’: The callback provided as
    parameter 1 is not a function.