ionic-geolocation-tutorial-example

Ionic Geolocation: In this tutorial, I’m going to teach you, “How to access user’s location by using Ionic Native (cordova-plugin-geolocation)” & Display locations on UI

Technology used:

  • Ionic 3
  • Ionic Native Geolocation (cordova-plugin-geolocation)

Step 1: Create New Ionic project

ionic start GeoDemo blank

Step 2: Add plugin

ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"

npm install --save @ionic-native/geolocation

Step 3: import plugin into src/app/app.module.ts

import { Geolocation } from '@ionic-native/geolocation';
Declare in providers
providers: [
 StatusBar,
 SplashScreen,
 Geolocation,
 {provide: ErrorHandler, useClass: IonicErrorHandler}
]

Step 4: Work with home.ts for accessing geolocation

export class HomePage {
  lat: any;
  lng: any;
  constructor(public navCtrl: NavController, public geo: Geolocation) {

  }

  ionViewDidLoad(){
    this.geo.getCurrentPosition().then( pos => {
      this.lat = pos.coords.latitude;
      this.lng = pos.coords.longitude;
    }).catch( err => console.log(err));
  }
}

Step 5: Display variables on home.html

Lat: {{ lat }}

Lang: {{ lng }}

Sundaravel M

About the author: Hey! It's me sundar. (Yea, I'm the founder of codesundar.com). I'm a passionate computer programmer who loves modern web and mobile development. feel free to reach me : Facebook - Twitter - Google+