我們今天來做一個ionic3版的GPS定位,我主要是參考ionic官網的簡單例子來做的,不足請指教。
來一個運行結果(打印經緯度):
開發步驟:
1:運行命令:來安裝GPS插件
ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation
注意:以上倆個命令都需要運行!
2:在app.module.ts中加入如下代碼:
import { Geolocation } from '@ionic-native/geolocation';
注意!!同時需要在app.module.ts的providers中加入Geolocation服務
3:在需要調用GPS定位的頁面加入如下代碼,我這邊是在home.html:
<button ion-button (click)="getGPS()">開始GPS</button>
4:在相應的ts文件中加入如下代碼(我已經把整個home.ts複製過來了),我這邊是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{ constructor(public navCtrl: NavController,private geolocation: Geolocation) { } public getGPS(){ this.geolocation.getCurrentPosition().then((resp) => { // resp.coords.latitude // resp.coords.longitude console.log(resp.coords.latitude,resp.coords.longitude); }).catch((error) => { console.log('Error getting location', error); }); } }
經過以上步驟就可以實現ionic3調用GPS實現對位置的獲取!
最重要的一點就是要把手機中的GPS打開而不是給應用賦予GPS權限!!