Showing posts with label Geolocation. Show all posts
Showing posts with label Geolocation. Show all posts

Thursday, August 16, 2018

Get user current location in ionic 2 | ionic 3

Get Geolocation (Latitude and Longitude) in Ionic 2 -






In this post, We will learn, how to get the user current latitude and longitude using the Geolocation native plugin (Ionic Plugin).

Geolocation : Geolocation is the identification of the real world geographic location of an object. Geolocation works through a pre-built GPS in a device. This provide location in the form of latitude and longitude of device.


Now, We are going to create a code flow for this. This is very simple to use.

Step 1: Install Geolocation plugin in your project by using below command -

ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation

For iOS platform you have to add below lines in project configuration.xml file -

<edit-config file="*-Info.plist" mode="merge" 
target="NSLocationWhenInUseUsageDescription"> <string>This app required to access your device location.</string> </edit-config>


Step 2 : Now add this plugin to your app's module (app.module.ts) -

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

Add "Geolocation" in providers -

 providers: [
    Geolocation,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]


Step 3 : Now use below code in your TS file where you want to use this plugin -

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

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

  public latitude:any;
  public longitude:any;

  constructor(public navCtrl: NavController, private geolocation: Geolocation) {

  }

  getLocation()
  {
    this.geolocation.getCurrentPosition().then((resp) => {
       this.latitude=resp.coords.latitude;
       this.longitude=resp.coords.longitude;
    }).catch((error) => {
      console.log('Error getting location'+JSON.stringify(error));
    });
  }


}

Step 4 : Use below code in your HTML file -
<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Geolocation Example</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="login">

  <h3>Current Latitude: {{latitude}}</h3>
  <h3>Current Longitude: {{longitude}}</h3>
  <button ion-button full primary (click)="getLocation()">Get Location</button>

</ion-content>



This is done from code side. All the best 👍