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 }}

 

Please login to download source code Login Here
Sundaravel M

About the author: Hi! I'm Sundaravel (codesundar), Founder of codesundar.com. I have been a Web, Mobile App developer, Author, and Teacher since 2014. I also worked as a software consultant for fortune 500 companies. I created codesundar.com to share my real-time knowledge in various technologies such as PhoneGap, Ionic, Flutter and more.