cordova-plugin-geolocation watchPosition()方法不起作用

时间:2016-09-26 09:12:54

标签: angular typescript cordova-plugins ionic2

我正在研究Ionic2-Angular2-Typescript应用程序。我试图使用Cordova的Geolocation插件,但是当我在http://ionicframework.com/docs/v2/native/geolocation/编辑器中调用watchPosition方法时,我会看到一些错误:

  

错误TS2339:属性'代码'类型' Geoposition |中不存在PositionError'

     

错误TS2339:属性' coords'类型' Geoposition |中不存在PositionError'

这是我的代码:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs';
import { Observable } from 'rxjs/Observable';
import { Geolocation, PositionError, Geoposition } from 'ionic-native';

export class LocationProvider {

    constructor(private http: Http) {}

    var subscription = Geolocation.watchPosition()
                          .filter((p) => p.code === undefined) //Filter Out Errors
                          .subscribe(position => {
  console.log(position.coords.longitude + ' ' + position.coords.latitude);
});
}

2 个答案:

答案 0 :(得分:5)

最后,我解决了我的问题如下:

this.subscription = Geolocation.watchPosition().subscribe(position => {
    if ((position as Geoposition).coords != undefined) {
      var geoposition = (position as Geoposition);
      console.log('Latitude: ' + geoposition.coords.latitude + ' - Longitude: ' + geoposition.coords.longitude);
    } else { 
      var positionError = (position as PositionError);
      console.log('Error ' + positionError.code + ': ' + positionError.message);
    }
});

答案 1 :(得分:0)

如何在回调函数中设置类型?如果您对错误不感兴趣,可以使代码更短。

像这样(未经测试):

this.subscription = Geolocation.watchPosition()
    .filter((p: any) => p['code'] === undefined) // Filter Out Errors
    .subscribe((position: GeoPosition) => {
        console.log(position.coords.longitude + ' ' + position.coords.latitude);
    });