Samuel Fraga Mateos Samuel Fraga Mateos - 2 months ago 139
TypeScript Question

cordova-plugin-geolocation watchPosition() method not working

I'm working on a Ionic2-Angular2-Typescript application. I'm trying to use Cordova's Geolocation plugin, but when I call watchPosition method like in http://ionicframework.com/docs/v2/native/geolocation/ editor shows me some errors:


Error TS2339: Property 'code' does not exist on type 'Geoposition | PositionError'.

Error TS2339: Property 'coords' does not exist on type 'Geoposition | PositionError'.


This is my code:

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);
});
}

Answer

Finally, I solved my problem as follows:

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);
    }
});