Ionic3+GPS定位

我们今天来做一个ionic3版的GPS定位,我主要是参考ionic官网的简单例子来做的,不足请指教。

来一个运行结果(打印经纬度):

Ionic3+GPS定位_第1张图片

开发步骤:

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()">开始GPSbutton>
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权限!!

你可能感兴趣的:(ionic3,GPS)