Ionic Geolocation Tutorial with Example

ionic-geolocation-example

In this tutorial, we're going to create a "Where I'm app" using ionic & cordova geo location plugin. The purpose of this app is getting user's current location

Let's start

Step 1:

First step, we need to create New Ionic project & change our working directory

ionic start whereiam blank
cd whereiam

Step 2:

Next, we need to add geolocation plugin

ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="give me your location"

npm install --save @ionic-native/geolocation

Step 3: After installing the cordova plugin and npm dependency, we need to declare it inside the app.module.ts

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { RouteReuseStrategy } from '@angular/router'; 

import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; 
import { SplashScreen } from '@ionic-native/splash-screen/ngx'; 
import { StatusBar } from '@ionic-native/status-bar/ngx'; 

import { AppComponent } from './app.component'; 
import { AppRoutingModule } from './app-routing.module'; 

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

@NgModule({
  declarations: [AppComponent], 
  entryComponents: [], 
  imports: [BrowserModule, IonicModule.forRoot({ mode: 'md' }), AppRoutingModule], 
  providers: [

    StatusBar,
    SplashScreen,
    Geolocation,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }

  ], 
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4:

<ion-content>
  <div class="center">
    <p>{{lat}} , {{lng}}</p>
    <ion-button fill="outline" (click)="getMyLocation()">Where I am?</ion-button>
  </div>
</ion-content>

Here we have created a button for accessing the location.when user clicks the button, we're caling getMyLocation() function which we created inside the home.ts file

import { Component } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  lat;
  lng;

  constructor(
    private geo: Geolocation
  ) { }

  getMyLocation() {
    this.geo.getCurrentPosition({
      enableHighAccuracy: true
    }).then(location => {
      this.lat = location.coords.latitude;
      this.lng = location.coords.longitude
    })
  }
}

For iOS

You need to add this line in your config.xml under <platform name="ios">

<edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
  <string>We need to access your location</string>
</edit-config>

Download Ionic Geolocation Example

Output

ionic-geolocation-example

Reference