【问题标题】:How can I use the GeoLocation PlugIn in Ionic 3?如何在 Ionic 3 中使用 GeoLocation 插件?
【发布时间】:2019-02-09 11:43:19
【问题描述】:

我无法在 Ionic 3 中使用 GeoLocation。我已经 看了几个教程并遇到了同样的问题。 这是我的设置。

PS C:\> ionic info

cli packages: (C:\Users\myID\AppData\Roaming\npm\node_modules)

    @ionic/cli-utils  : 1.9.2
    ionic (Ionic CLI) : 3.9.2

global packages:

    Cordova CLI : 8.1.2 (cordova-lib@8.1.1)

local packages:

    @ionic/app-scripts : 3.1.0
    Cordova Platforms  : none
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v8.10.0
    npm               : 5.6.0
    OS                : Windows 10

PS C:\>
PS C:\>
PS C:\>
PS C:\> ionic cordova plugin list
> cordova plugin ls
v Running command - done!
cordova-plugin-geolocation 4.0.1 "Geolocation"
PS C:\>
PS C:\>
PS C:\>

在设置 hello-world/空白地理位置应用程序时,我在引用 地理位置插件。

// app.module.ts
import { Geolocation } from '@ionic-native/geolocation';
// ...
providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Geolocation  // <-- Errors here
  ]

我可以通过添加 ngx 后缀来解决这个错误:

// app.module.ts
import { Geolocation } from '@ionic-native/geolocation/ngx';
// ...
providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Geolocation  // OK now
  ]

但是,当我真正去使用它时:

//home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation/ngx';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  lat: any;
  lng: any;

  constructor(public navCtrl: NavController,
    public geo: Geolocation) {
  }

  ionViewDidLoad() {
    this.geo.getCurrentPosition().then(pos => {
      this.lat = pos.coords.latitude;
      this.lng = pos.coords.longitude;
    }).catch(err => console.log(err));
  }

}

我开始收到此错误:

TypeError: Object(...) is not a function at Geolocation.getCurrentPosition

注释掉对getCurrentPosition 的调用会使错误消失。

我错过了什么?我是否得到了错误的插件版本?有没有办法 想知道哪个适用于 Ionic 3 的最新版本?

【问题讨论】:

    标签: ionic-framework ionic3


    【解决方案1】:

    您是否安装了 Geolocation 插件 v3?可以看到here,命令是:

    $ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
    $ npm install --save @ionic-native/geolocation@4
    

    安装后,您必须将插件导入 app.module 以及 home.ts

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

    使用插件的代码是对的,不需要修改。

    this.geo.getCurrentPosition().then(pos => {
       this.lat = pos.coords.latitude;
       this.lng = pos.coords.longitude;
    }).catch(err => console.log(err));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-17
      • 2018-08-06
      • 1970-01-01
      • 2018-03-11
      • 2018-06-06
      • 1970-01-01
      • 2018-10-20
      • 2018-07-22
      相关资源
      最近更新 更多