This guide will walk you through writing a simple Ionic framework application that utilizes Cordova Geolocation plugin. It is also important to mention that we will cover what is now known as Angular (Angular 2|4), not what was used to be known as Angular 1. If you came here for the original Ionic 1 example them please find it here.
 
You will also be able to learn how to work with Ionic native implementation as we will try to use this walkthrough as close to the Ionic ecosystem as possible. On the other hand, if you came here looking for a pure JavaScript Google Maps solution then, by all means, find it here.
 
This guide will not require a real smartphone device as Cordova Geolocation plugin also works in all modern browsers, but I encourage you to try it anyway.
 
 

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

 
Is Ionic (2 or 3) causing you problems? Are you struggling with your application? Trust me, I was in the same situation like you. If you require more information beyond the subject of this article, you will probably find it in a list below. Take a look; if there’s a topic not covered here, leave me a comment, and I will do my best to cover it.
 
 

Preparations

 
First things first, you need to have an up and ready Ionic [2|3] development environment. Plus, as I don’t wont to confuse you, what am I now simply referring to as Ionic was known as Ionic 2|4. As such, I will refer to it through that name; there will be no version numbers.
 
Make sure you have these:
 
  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
 
If you don’t have a prior Ionic installation find more information here: Ionic [2|3] | Installation Guide.
 

1. Update Ionic CLI

 
The latest NodeJS version is a must-have. Without it, we may have a problem while installing/updating Cordova and Ionic. But you can always try to use any recent version.
 
One last thing, your development environment needs to be up and running, just make sure it’s up to date; older versions may not work with this tutorial:
 
npm install -g ionic cordova
 
or to do a simple update:
 
npm update -g ionic cordova
 
 

2. Create A New Project

 
ionic start IonicCordovaGeolocation blank
cd IonicCordovaGeolocation 
 
You can find a working example at the end of this article if you’re an impatient type. Just follow the provided README.md instructions.
 
Warning: As some of you don't have a prior Ionic CLI experience, from this point and on, every time I tell you to execute something, do that inside an example project folder.
 

3. Add Required Platform

 
Add Android platform:
 
ionic cordova platform add android
 
MacOS users can also add iOS platform:
 
ionic cordova platform add ios
 

3. Install Ionic Native Geolocation Plugin

 
A bit of warning if you don’t have a prior Ionic Native experience, it’s just a layer around various Cordova plugins. This way, among other things, you don’t need to mix TypeScript and vanilla JavaScript found in Cordova plugins.
 
ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
npm install --save @ionic-native/geolocation
 

Example

 
First take a look at this embedded example:
 
Ionic 2 Page Navigation
 

Source Walkthrough

 
The first thing we need to do is include Google Maps SDK library into an application index.html file. SDK is not a necessity here, but our example will not work without it.
 
Open src folder and edit index.html file. Add this line above cordova.js line:
 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<API KEY>" type="text/javascript"></script>
 
It should look like this:
 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<API KEY>" type="text/javascript"></script>
<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>
 
If you carefully look, you’ll notice that provided Google Maps link is not correct. That’s because it’s missing a API key, and you can acquire it here. Just follow the instructions as it’s free of charge.
 
If your Google Maps link looks like this:
 
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
 
Remove the sensor parameter, it’s no longer important. Google Maps library will throw an error if you leave it as it is:
 
Google Maps API warning: SensorNotRequired: https://developers.google.com/maps/documentation/javascript/error-messages
 
Next, include Geolocation plugin into app.module.ts file:
 
import { Geolocation } from '@ionic-native/geolocation';
 
There’s one more step we need to do. As you are probably intending to use this code on a smartphone, it’s important to initialize it after “the device is ready” state has occurred. In Ionic, it is also known as when IonView component is active.
 
/* Initialize the map only when Ion View is loaded */
ionViewDidLoad(){
	this.initializeMap();
}
 
Function initializeMap will initialize our map:
 
initializeMap() {

	let locationOptions = {timeout: 10000, enableHighAccuracy: true};

	this.geolocation.getCurrentPosition(locationOptions).then((position) => {

		let options = {
		  center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
		  zoom: 16,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		/* Show our lcoation */
		this.map = new google.maps.Map(document.getElementById("map_canvas"), options);

		/* We can show our location only if map was previously initialized */
		this.showMyLocation();

	}).catch((error) => {
	  console.log('Error getting location', error);
	});
} 
 
Continue to the next page

  • Nuatga

    I have tried this example but this is not working on android device what is the reason?

    • Prabir Kundu

      Same here…have u got any solution?

      • There’s a simple reason, this article is almost two years old. But I will update it for you tomorrow.

        • Prabir Kundu

          OK…thank u.actually it is running fine in browser but is not working in real device

  • Suresh

    Hi,
    Is it possible to use this Plugin to check if the GPS Module is enabled on the device. Or is there any other plugin which i could use to check this.
    Thanks
    Suresh

  • Hm, could you please tell me what are you trying to do? This looks like a desktop browser error as hybrid mobile app should not be able to throw this error.

    • Pepito Perez

      Hi, thanks for reply, that error was running the command “ionic run android -l” I quit the “-l” and works!! but even there, the app told me “not sufficient permission” then I re-add the platform and reboot the device, then works