Ionic 3 Geolocation and Geocoder Example – Device Latitude, Longitude and Address

UPDATED(26/03/19) for latest CLI 4.12.0 In this post, we will implement Geolocation and Geocoder plugins in Ionic 3 application. Using Geolocation service we can get Lattitude, Longitude, Accuracy of location, Speed, Altitude etc of the device. After that Latitude and Longitude can be used to get Addresses available on these coordinates. To fetch address from…

By.

•

min read

UPDATED(26/03/19) for latest CLI 4.12.0

In this post, we will implement Geolocation and Geocoder plugins in Ionic 3 application. Using Geolocation service we can get Lattitude, Longitude, Accuracy of location, Speed, Altitude etc of the device. After that Latitude and Longitude can be used to get Addresses available on these coordinates. To fetch address from coordinates of the device, we use Geocoder service.

Here we will discuss on How to use Geolocation and Geocoder in Ionic 3

So, let’s begin …

Before we start with application make sure that your system is having an updated version of NodeJS installed.

Create a new Ionic Application

Install latest version of Ionic and Cordova CLI.

$ npm install -g ionic cordova

Now we will create a new blank application

$ ionic start Ionic3Geolocation_Geocoder blank --type=ionic-angular

After the application is created, go to the root using the CD command

$ cd Ionic3Geolocation_Geocoder

If your system is having Visual Studio code(VS Code) installed, use $ code .  command to open the project in VS Code

Install the Cordova and Ionic Native plugins

Geolocation

$ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
$ npm install --save @ionic-native/geolocation@4

If you see this error, don’t worry just rerun commands 🙂

 

 

 

 

 

This plugin will use device location service to fetch latitude, longitude, accuracy, altitude, altitudeAccuracy, altitudeAccuracy, heading, speed

Geocoder

$ ionic cordova plugin add cordova-plugin-nativegeocoder
$ npm install --save @ionic-native/native-geocoder@4

It will return address for provided coordinates, and also do reverse geocoding.

Add this plugin in the application’s module file

In app.module.ts, import plugin and add in imports array.

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

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

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Geolocation,
    NativeGeocoder,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

In home.html, add following HTML

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 3 Geolocation & Geocoder Demo
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>Get Location</h1>

  <button ion-button (click)="getGeolocation()">Get Location</button>
  <button ion-button (click)="watchLocation()">Watch Location Updates</button>
  <button ion-button (click)="stopLocationWatch()">Stop Location Watch</button>
  <div *ngIf="geoLatitude">
    <p>Latitude : {{geoLatitude}}</p>
    <p>Longitude : {{geoLongitude}}</p>
    <p>Accuracy : {{geoAccuracy}}</p>
    <p class="address-text">

      <span class="watch-text" *ngIf="isWatching; else notWatching">
        Watching Location
      </span>
      <ng-template #notWatching>
        Location Watch Stopped
      </ng-template>

      <br>Address : {{geoAddress }}
    </p>
  </div>
</ion-content>

Here we have three buttons to fetch location coordinates, Watch location updates and stop location updates. After successfully fetching we are showing information returned.

Update component with methods

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';

import { Geolocation } from '@ionic-native/geolocation';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  geoLatitude: number;
  geoLongitude: number;
  geoAccuracy:number;
  geoAddress: string;
 
  watchLocationUpdates:any; 
  loading:any;
  isWatching:boolean;
 
  //Geocoder configuration
  geoencoderOptions: NativeGeocoderOptions = {
    useLocale: true,
    maxResults: 5
  };
  constructor(
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder
  ) {
  }
 
  
    //Get current coordinates of device
    getGeolocation(){
      this.geolocation.getCurrentPosition().then((resp) => {
        this.geoLatitude = resp.coords.latitude;
        this.geoLongitude = resp.coords.longitude; 
        this.geoAccuracy = resp.coords.accuracy; 
        this.getGeoencoder(this.geoLatitude,this.geoLongitude);
       }).catch((error) => {
         alert('Error getting location'+ JSON.stringify(error));
       });
    }
  
    //geocoder method to fetch address from coordinates passed as arguments
    getGeoencoder(latitude,longitude){
      this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions)
      .then((result: NativeGeocoderReverseResult[]) => {
        this.geoAddress = this.generateAddress(result[0]);
      })
      .catch((error: any) => {
        alert('Error getting location'+ JSON.stringify(error));
      });
    }
  
    //Return Comma saperated address
    generateAddress(addressObj){
        let obj = [];
        let address = "";
        for (let key in addressObj) {
          obj.push(addressObj[key]);
        }
        obj.reverse();
        for (let val in obj) {
          if(obj[val].length)
          address += obj[val]+', ';
        }
      return address.slice(0, -2);
    }
  
  
    //Start location update watch
    watchLocation(){
      this.isWatching = true;
      this.watchLocationUpdates = this.geolocation.watchPosition();
      this.watchLocationUpdates.subscribe((resp) => {
        this.geoLatitude = resp.coords.latitude;
        this.geoLongitude = resp.coords.longitude; 
        this.getGeoencoder(this.geoLatitude,this.geoLongitude);
      });
    }
  
    //Stop location update watch
    stopLocationWatch(){
      this.isWatching = false;
      this.watchLocationUpdates.unsubscribe();
    }

}

Above code is having inline comments to explain methods, we are using Ionic Loader component here. Geolocation and Geocoder methods with configuration definitions.

Pinch of CSS styling in home.scss

page-home {
    .address-text{
        text-align: center;
        font-size: 20px;
    }
    .watch-text{
        font-size: 18px;
    }
}

That’s it you can now test your application in a real device after building apk using this command $ ionic cordova build android 

Let me know if you face any issue in implementing this

Happy coding 🙂

10 responses to “Ionic 3 Geolocation and Geocoder Example – Device Latitude, Longitude and Address”

  1. Gaara Avatar
    Gaara

    •

    Hi, anyone has problem with getCurrentPosition? Sometimes it not getting current position, it get location which is one week ago.

  2. KESHAV GODANI Avatar
    KESHAV GODANI

    •

    Cannot find name ‘NativeGeocoderReverseResult’.

    [17:55:17] typescript: E:/Users/RISINGBEE/git/bob-app/src/pages/cmn/login/login.ts, line: 1001
    Cannot find name ‘NativeGeocoderReverseResult’.

    L1000: this.nativeGeocoder.reverseGeocode(resp.coords.latitude, resp.coords.longitude, options)
    L1001: .then((result: NativeGeocoderReverseResult[]) => {
    L1002: this.userlocation = result[0].toString();

  3. Neevan Avatar
    Neevan

    •

    Hey there,
    Suppose we have a map with a draggable marker on it & as soon as the user drags the marker and place anywhere the marker should generate the new location and display the new location’s formatted address.

    How can we do that? Can you make a tutorial on that please?

    1. Rish Avatar
      Rish

      •

      Using Ionic 3 Framework

  4. ram Avatar
    ram

    •

    what about if i want autocomplete to work after 3 characters entered ? do you have any solution for it?
    thanks by advance

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Ram, please check updated code for latest CLI, can you please explain the requirement a bit more? I am unable to find autocomplete in this post 🙂

  5. Rish Avatar
    Rish

    •

    Thanks for the amazing tutorial. Very Helpful but by this method we get complete address like [Locality, City, State, CountryName].
    Now how can I display only street / city name?

  6. Harsh Vijay Shah Avatar
    Harsh Vijay Shah

    •

    NativeGeocoder is unable to assign it.

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Harsh can you check code in source file? it should work fine. let me know if you still face issues

      1. Harsh Vijay Shah Avatar
        Harsh Vijay Shah

        •

        Getting errors

        ERROR Error: Uncaught (in promise): Error: Can’t resolve all parameters for HomePage: ([object Object], [object Object], [object Object], ?, [object Object], [object Object], [object Object]).
        Error: Can’t resolve all parameters for HomePage: ([object Object], [object Object], [object Object], ?, [object Object], [object Object], [object Object]).

Leave a Reply

Your email address will not be published. Required fields are marked *