ถ้าเป็น iOS ต้องเพิ่ม config ด้วย
สร้างโปรเจ็กส์ใหม่
[code]
ionic start geolocation blank
[/code]
[code]
cd geolocation
ionic serve
[/code]
ติดตั้ง plugin
[code]
$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install –save @ionic-native/geolocation
[/code]
src/app/app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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 { Geolocation } from '@ionic-native/geolocation'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; @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 {} |
src/pages/home/home.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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 { geo: any; constructor(public navCtrl: NavController, private geolocation: Geolocation) { this.geo = geolocation; this.geo.getCurrentPosition().then((resp) => { // resp.coords.latitude // resp.coords.longitude console.log('resp.coords.latitude : ', resp.coords.latitude); console.log('resp.coords.longitude : ', resp.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 console.log('data.coords.latitude : ', data.coords.latitude); console.log('data.coords.longitude : ', data.coords.longitude); }); } } |
getCurrentPosition(options)
Get the device’s current position.
watchPosition(options)
Watch the current device’s position. Clear the watch by unsubscribing from Observable changes.
ความแตกต่างของทั้ง 2 แบบ
เราทดสอบเปิด Tab ที่เรียกหน้านี้ใน Chrome เปิดครั้งแรกทำงานทั้ง getCurrentPosition(options)
และ watchPosition(options)
(ดูที่หน้า Debug-F12) แต่พอสลับไป Tab อื่นของ Chrome แล้วกลับมา Tab นี้อีก ปรากฏว่าทำงานแค่ watchPosition(options)
ทำให้สรุปได้ว่า
getCurrentPosition(options)
ทำงานแค่ครั้งเดียวจบ ส่วนwatchPosition(options)
ทำงานทุกครั้งที่เราเลือกที่ Tab นี้
Note: watchPosition()
จะทำงานต่อเนื่องก็ต่อเมื่ออยู่ใน constructor()
Link