Hi Friends,

Hope you are all well. In this post let’s discuss about Geolocation and Geocoding in your Ionic 2 apps.

One of the more commonly used features in almost all mobile apps nowadays is location based services. i.e., we identify the location of the user and provide services to him accordingly. So to find the location of a particular user anywhere on the face of the earth is to get the latitude and longitude of where he is located and then try to decide the location using those coordinates.

We use the Geolocation plugin to get the latitude and longitude of the location where the devices is present, we then use the geocoding plugin to perform a reverse geocoding wherein we pass the latitude and longitude to get the name of the place. Let’s see how to do this in a simple way.

Let’s begin.

A screencast of this post

Complete code of this post is available here.

First let’s scaffold out an ionic 2 app using the cli.

We now need 2 plugins to perform the task. So let’s go ahead and install them.

ionic plugin add cordova-plugin-geolocation ionic plugin add cordova-plugin-nativegeocoder 1 2 ionic plugin add cordova - plugin - geolocation ionic plugin add cordova - plugin - nativegeocoder

Now since Ionic native 3.1.x it is required to install the wrappers for these plugins as well.

npm install @ionic-native/geolocation --save npm install @ionic-native/native-geocoder --save 1 2 npm install @ ionic - native / geolocation -- save npm install @ ionic - native / native - geocoder -- save

Now open up app.module.ts and modify it as shown below.

import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Geolocation } from '@ionic-native/geolocation'; import { NativeGeocoder } from '@ionic-native/native-geocoder'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, Geolocation, NativeGeocoder, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import { NgModule , ErrorHandler } from '@angular/core' ; import { IonicApp , IonicModule , IonicErrorHandler } from 'ionic-angular' ; import { MyApp } from './app.component' ; import { HomePage } from '../pages/home/home' ; import { StatusBar } from '@ionic-native/status-bar' ; import { SplashScreen } from '@ionic-native/splash-screen' ; import { Geolocation } from '@ionic-native/geolocation' ; import { NativeGeocoder } from '@ionic-native/native-geocoder' ; @ NgModule ( { declarations : [ MyApp , HomePage ] , imports : [ IonicModule . forRoot ( MyApp ) ] , bootstrap : [ IonicApp ] , entryComponents : [ MyApp , HomePage ] , providers : [ StatusBar , SplashScreen , Geolocation , NativeGeocoder , { provide : ErrorHandler , useClass : IonicErrorHandler } ] } ) export class AppModule { }

We will just have one button on the homepage which upon clicking will show us the location or the country name in a toast.

Open up home.html and add the below code inbetween the <ion-content> tags.

<button ion-button (click)="geolocate()">Get Location</button> 1 < button ion - button ( click ) = "geolocate()" > Get Location < / button >

Open up home.ts and modify it as shown below.

import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Geolocation, Geoposition } from '@ionic-native/geolocation'; import { NativeGeocoder, NativeGeocoderReverseResult } from '@ionic-native/native-geocoder'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, public geolocation: Geolocation, public geocoder: NativeGeocoder, public toaster: ToastController, public locac: LocationAccuracy) { } geolocate() { let options = { enableHighAccuracy: true }; this.geolocation.getCurrentPosition(options).then((position: Geoposition) => { this.getcountry(position); }).catch((err) => { alert(err); }) } getcountry(pos) { this.geocoder.reverseGeocode(pos.coords.latitude, pos.coords.longitude).then((res: NativeGeocoderReverseResult) => { let country = this.toaster.create({ message: res.countryName, duration: 4000 }); country.present(); }) } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import { Component } from '@angular/core' ; import { NavController , ToastController } from 'ionic-angular' ; import { Geolocation , Geoposition } from '@ionic-native/geolocation' ; import { NativeGeocoder , NativeGeocoderReverseResult } from '@ionic-native/native-geocoder' ; @ Component ( { selector : 'page-home' , templateUrl : 'home.html' } ) export class HomePage { constructor ( public navCtrl : NavController , public geolocation : Geolocation , public geocoder : NativeGeocoder , public toaster : ToastController , public locac : LocationAccuracy ) { } geolocate ( ) { let options = { enableHighAccuracy : true } ; this . geolocation . getCurrentPosition ( options ) . then ( ( position : Geoposition ) = > { this . getcountry ( position ) ; } ) . catch ( ( err ) = > { alert ( err ) ; } ) } getcountry ( pos ) { this . geocoder . reverseGeocode ( pos . coords . latitude , pos . coords . longitude ) . then ( ( res : NativeGeocoderReverseResult ) = > { let country = this . toaster . create ( { message : res . countryName , duration : 4000 } ) ; country . present ( ) ; } ) } }

We are simply using the geolocation.getCurrentPosition() to get the latitude and longitude coordinates of the device’s location and then passing it along to getcountry().

In getcountry() we are simply performing a reversegeocoding and then passing the country name to a toast.

(Forward Geocoding means to pass the name of a location and get it’s latitude and longitude coordinates whereas reverse geocoding implies the opposite).

Now run the app on your device and you should see the name of the country you live at present on your mobile device.

So far so good., but assume that your location settings in your mobile is turned off. Now if you click on the button, it doesn’t even throw up an error right ? We need to fix this too.

To request the user to turn on his location settings in that case, we have another plugin called location-accuracy that we could use.

To install the location-accuracy plugin simply type in the below command in your terminal.

ionic plugin add cordova-plugin-request-location-accuracy 1 ionic plugin add cordova - plugin - request - location - accuracy

Install the native wrapper as well using the below command.

npm install @ionic-native/location-accuracy --save 1 npm install @ ionic - native / location - accuracy -- save

Now open up app.module.ts and add this plugin as well. The final app.module.ts file would look as shown below.

import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Geolocation } from '@ionic-native/geolocation'; import { NativeGeocoder } from '@ionic-native/native-geocoder'; import { LocationAccuracy } from '@ionic-native/location-accuracy'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, Geolocation, NativeGeocoder, LocationAccuracy, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import { NgModule , ErrorHandler } from '@angular/core' ; import { IonicApp , IonicModule , IonicErrorHandler } from 'ionic-angular' ; import { MyApp } from './app.component' ; import { HomePage } from '../pages/home/home' ; import { StatusBar } from '@ionic-native/status-bar' ; import { SplashScreen } from '@ionic-native/splash-screen' ; import { Geolocation } from '@ionic-native/geolocation' ; import { NativeGeocoder } from '@ionic-native/native-geocoder' ; import { LocationAccuracy } from '@ionic-native/location-accuracy' ; @ NgModule ( { declarations : [ MyApp , HomePage ] , imports : [ IonicModule . forRoot ( MyApp ) ] , bootstrap : [ IonicApp ] , entryComponents : [ MyApp , HomePage ] , providers : [ StatusBar , SplashScreen , Geolocation , NativeGeocoder , LocationAccuracy , { provide : ErrorHandler , useClass : IonicErrorHandler } ] } ) export class AppModule { }

Open up home.ts file and modify it as shown below.

import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Geolocation, Geoposition } from '@ionic-native/geolocation'; import { NativeGeocoder, NativeGeocoderReverseResult } from '@ionic-native/native-geocoder'; import { LocationAccuracy } from '@ionic-native/location-accuracy'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, public geolocation: Geolocation, public geocoder: NativeGeocoder, public toaster: ToastController, public locac: LocationAccuracy) { } geolocate() { let options = { enableHighAccuracy: true }; this.locac.canRequest().then((res: boolean) => { if (res) { this.locac.request(this.locac.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => { this.geolocation.getCurrentPosition(options).then((position: Geoposition) => { this.getcountry(position); }).catch((err) => { alert(err); }) }, (error) => { alert(error); }) } }) } getcountry(pos) { this.geocoder.reverseGeocode(pos.coords.latitude, pos.coords.longitude).then((res: NativeGeocoderReverseResult) => { let country = this.toaster.create({ message: res.countryName, duration: 4000 }); country.present(); }) } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 import { Component } from '@angular/core' ; import { NavController , ToastController } from 'ionic-angular' ; import { Geolocation , Geoposition } from '@ionic-native/geolocation' ; import { NativeGeocoder , NativeGeocoderReverseResult } from '@ionic-native/native-geocoder' ; import { LocationAccuracy } from '@ionic-native/location-accuracy' ; @ Component ( { selector : 'page-home' , templateUrl : 'home.html' } ) export class HomePage { constructor ( public navCtrl : NavController , public geolocation : Geolocation , public geocoder : NativeGeocoder , public toaster : ToastController , public locac : LocationAccuracy ) { } geolocate ( ) { let options = { enableHighAccuracy : true } ; this . locac . canRequest ( ) . then ( ( res : boolean ) = > { if ( res ) { this . locac . request ( this . locac . REQUEST_PRIORITY_HIGH_ACCURACY ) . then ( ( ) = > { this . geolocation . getCurrentPosition ( options ) . then ( ( position : Geoposition ) = > { this . getcountry ( position ) ; } ) . catch ( ( err ) = > { alert ( err ) ; } ) } , ( error ) = > { alert ( error ) ; } ) } } ) } getcountry ( pos ) { this . geocoder . reverseGeocode ( pos . coords . latitude , pos . coords . longitude ) . then ( ( res : NativeGeocoderReverseResult ) = > { let country = this . toaster . create ( { message : res . countryName , duration : 4000 } ) ; country . present ( ) ; } ) } }

If the location is not turned on, we show up a prompt requesting the user to turn it on, once the location settings are turned on then we can simply use the geolocation and geocoding plugins to get the location of the user.

Hope this helped you guys. If you found this helpful, kindly share it with someone and help them too.

Thanks for reading; peace..