How to get latitude and longitude value in ionic
First we need to create a blank project after created project follow some step
creating project : ionic start geolocation blank
Step 1 : Install the Cordova and Ionic Native plugins
$ ionic cordova plugin add cordova-plugin-geolocation –variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
$ npm install --save @ionic-native/geolocation
Step 2 : Add this plugin to your app's module
app.module.ts
you will find this file in your project
import { Geolocation } from '@ionic-native/geolocation';
or
providers: [
StatusBar,
SplashScreen,Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
Step 3 : Add code your home.ts file
import { Geolocation } from '@ionic-native/geolocation';
...
constructor(private geolocation: Geolocation) {}
...
this.geolocation.getCurrentPosition().then((pos) => {
// pos.coords.latitude
// pos.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
});
Get Full code
app.module.ts
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 { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Geolocation } from '@ionic-native/geolocation';
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
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) {
//=============== Get latitude and longitude =====================================
this.geolocation.getCurrentPosition().then((pos) => {
console.log(pos);
this.latitude = pos.coords.latitude
this.longitude = pos.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});
//==================================================
}
}
home.html
<ion-header>
<ion-navbar color="danger">
<ion-title>
JawabAdda
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<p>
<strong>latitude</strong> : {{latitude}}
</p>
<p>
<strong>longitude</strong> : {{longitude}}
</p>
</ion-content>