Reputation:
I'm building an ionic app with capacitor. Currently i'm running in a use case where I need to use GPS to get user location.
After digging out for almost 2hrs, I found out that fused location is the way to go.
From capacitor official documents I couldn't find relevant info on how to call fused location to get geo location on android. Below is the tested code that runs on browsers but fails on device.
import { Geolocation } from '@capacitor/core';
export class HomePage implements OnInit {
latitude: number;
longitude: number;
constructor() {}
async getCurrentPosition() {
const coordinates = await Geolocation.getCurrentPosition();
console.log('Current', coordinates);
}
watchPosition() {
Geolocation.watchPosition({}, (position, err) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude
console.log(position);
})
}
}
Upvotes: 0
Views: 477
Reputation: 12139
If you don't see the position in the template you probably need to run the callback inside the NgZone:
import { Component, NgZone } from '@angular/core';
// ...
constructor(
private ngZone: NgZone,
) { }
watchPosition() {
this.locationWatchId = Geolocation.watchPosition(this.geolocationOptions, (position, err) => {
this.ngZone.run(() => {
if (err) {
console.error('Failed to watch position.', err);
}
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude
console.log(position);
});
});
}
Upvotes: 1