In this tutorial, you will learn, how to get the latitude and longitude using the Geolocation native plugin on the Ionic 2 framework. Nowaday Geolocation used for many purposes. 

1. To find the fraudulent account activity using the location service. Google and Facebook using the geolocation to secure the account.

2. To refer and advertise the relevant products based on the location.

3. To find the route and places. By using the Google Map services, you can easily find the route and places


iOS Emulator Preview

To get the Geolocation information such as latitude and longitude, you need to install the Ionic 2 Geolocation plugin. 

Create a new Ionic 2 project using.

ionic start gps blank --v2

Install the Geolocation plugin using the below command.

ionic plugin add cordova-plugin-geolocation --save
npm install --save @ionic-native/geolocation

Now import the Geolocation plugin to the app.module.ts file.

import { Geolocation } from '@ionic-native/geolocation';

Include the Geolocation in the provider of the app.module.ts file.

providers: [Device,Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler}

Create a button with the click event on the home.html file, which is used to get the latitude and longitude.

<button ion-button color="danger" (click)="getGeo()" > GetGeo </button>

Now import the Geolocation class in the home.ts file.

import { Geolocation } from '@ionic-native/geolocation';

Create a Geolocation reference in the constructor.

constructor(private geolocation: Geolocation)


Use the getCurrentPosition() method of the Geolocation class to get the latitude and longitude.

this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
}).catch((error) => {
alert('Error getting location'+JSON.stringify(error));

That' all. You are done.  You can preview this using the Android and iOS emulator.

Add iOS platform using the below command. However, in Mac OS, the iOS platform added by default when creating the new Ionic 2 project.

ionic platform add ios

Run using the iOS emulator.

ionic run ios

To preview this app on the Android emulator, first, add the Android platform.

ionic platform add android

Use the below command to run on the Genymotion emulator(Android emulator).

ionic run android

If the Geolocation is enabled on your device, the error alert message will be displayed.

Xcode emulator(iOS SE)
Genymotion emulator(Android)

Below is the Ionic 2 information while writing this tutorial.

Cordova CLI: 6.5.0 
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.3.7
ios-deploy version: Not installed
ios-sim version: 5.0.13 
OS: macOS Sierra
Node Version: v6.10.0
Xcode version: Xcode 8.2.1