It also happens that the behavior of the phone varies depending on the accuracy you have (example: in iOS, it's necessary to "true" in enableHighAccuracy).
I also had many issues with the location capability and ended up solving it as next:
create api.provider and inject into component:
-geo options declaration:
private geoOptions: GeolocationOptions = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 12000
};
-onInit called from constructor:
public onInit(): Promise<any> {
return new Promise<any>((resolve: (value?: boolean | any) => void, reject: (reason?: any) => void) => {
this.getCurrentPosition().subscribe((response: any) => {
resolve(response);
}, (err: any) => {
reject(err);
});
});
}
-constructor that already handles getCurrentPosition errors and varies the accuracy options to call back before executing watchPosition:
constructor(public api: Api, private gps: Geolocation, private toast: ToastController) {
const locationSubscription = this.isLocationActive.subscribe((response: any) => {
const initExecute = () => {
this.onInit()
.then((val: any) => {
this.watchPosition().subscribe();
locationSubscription.unsubscribe();
}).catch((reason: any) => {
// if fails, turn enableHighAccuracy options (some Android devices do not have HighAccuracy available)
this.geoOptions.enableHighAccuracy = !this.geoOptions.enableHighAccuracy;
initExecute();
});
};
if (response && (response as boolean).toString().toLowerCase() === "true") {
initExecute();
}
});
}
-the currentPosition wrapped method:
public getCurrentPosition(): Observable<Geoposition> {
// Create an Observable that will start listening to geolocation updates
// when a consumer subscribes
return Observable.create((observer: Observer<Geoposition>) => {
this.gps.getCurrentPosition(this.geoOptions).then((response: any) => { // your todo validator
// this.validateGeolocationResponse(err, observer, true);
}).catch((err: any) => {
// your todo validator
// this.validateGeolocationResponse(err, observer, true);
});
// When the consumer unsubscribes, clean up data ready for next subscription.
// return { unsubscribe() { navigator.geolocation.clearWatch(watchId); }};
});
}
-and finally, the watchPosition method:
public watchPosition(): Observable<Geoposition> {
return Observable.create((observer: Observer<Geoposition>) => {
this.gps.watchPosition(this.geoOptions).subscribe((response: any) => {
// your validation method if coords are returned
this.validateGeolocationResponse(response, observer);
}, (err: any) => {
// your validation method if coords are returned
this.validateGeolocationResponse(err, observer, true);
});
});
}
-Tip
Create a ReplaySubject to store the last right coord values. It doesn't always return successfully, therefore it is advisable to search for the latest successes and return them to your subscriber if the current ones fail.
E.g.:
public currentLocation = new ReplaySubject<Geoposition>(2);
Blessings for you too!