Reading the library documentation I could read this:
/**
* Watch the current device's position. Clear the watch by unsubscribing from
* Observable changes.
*
* ...
*
* @param {GeolocationOptions} options The [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions).
* @returns {Observable<Geoposition | PositionError>} Returns an Observable that notifies with the [position](https://developer.mozilla.org/en-US/docs/Web/API/Position) of the device, or errors.
*/
watchPosition(options?: GeolocationOptions): Observable<Geoposition | PositionError>;
As you see, the method returns an Observable<Geoposition | PositionError>. So, the error you are getting is because the property Geoposition.coords.latitude exists in a Geoposition interface, but it doesn't exists in a PositionError, so it doesn't exists in a Observable<Geoposition | PositionError>. This is a Typescript error.
You hace two choices then:
- Make the data type any, but you will not be checking for PositionError:
async getMyLocation1() {
let watch = await this.geolocation.watchPosition();
watch.subscribe((data:any) => {
console.log(data.coords.latitude);
});
}
- Change the code to verify if the data accomplish a Geoposition interface (this interface check was inspired by this):
async getMyLocation1() {
let watch = await this.geolocation.watchPosition();
watch.subscribe((data:any) => {
if (this.isGeoposition(data)) {
console.log(data.coords.latitude);
} else {
console.log('Error getting location');
}
});
}
isGeoposition(data: any): data is Geoposition {
return (data.coords !== undefined && data.timestamp !== undefined);
}
By the way, if you are wondering when would the watchPosition method return a PositionError, one example would be when the browser asks for your location, and you deny the permission it will generate a PositionError instead of a Geoposition.