美文网首页
1.17 ionic3入门——geolocation定位

1.17 ionic3入门——geolocation定位

作者: 杨啊杨_fb52 | 来源:发表于2018-09-29 21:54 被阅读0次

geolocation定位是调用手机gps,获取坐标的,在实际中用处较广
(1)安装插件

ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="允许App使用GPS定位功能"
npm install --save @ionic-native/geolocation

(2)app.moudule.ts中引入及声明

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

在providers中声明Geolocation

  providers: [
    StatusBar,
    SplashScreen,
    Camera,
    ImagePicker,
    Geolocation,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]

(3)在使用的页面中引用声明

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

按照官方的还引用了Platform

import { NavController,Platform} from 'ionic-angular';

在构造函数中声明

  constructor(public navCtrl: NavController,public menuCtrl: MenuController,private platform: Platform,private geolocation: Geolocation) {

  }

(4)使用

//官方
  gps(){
    this.platform.ready().then(() => {

      // get current position
      this.geolocation.getCurrentPosition().then(pos => {
        alert('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
      });

      const watch = this.geolocation.watchPosition().subscribe(pos => {
        alert('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
      });

      // to stop watching
      watch.unsubscribe();

    });
  }
  gps2(){
    this.geolocation.getCurrentPosition().then((resp) => {
      // resp.coords.latitude
      // resp.coords.longitude
      alert(resp.coords.latitude+','+resp.coords.longitude);
    }).catch((error) => {
      console.log('Error getting location', error);
    });

  }

敲黑板,注意了
ios 必须在info.plist加上权限设置
Privacy - Location When In Use Usage Description——————允许app使用GPS定位
Privacy - Location Always Usage Description—————————始终允许App使用GPS定位功能

相关文章

网友评论

      本文标题:1.17 ionic3入门——geolocation定位

      本文链接:https://www.haomeiwen.com/subject/fdtioftx.html