Бывает и так, что поведение телефона зависит от вашей точности (пример: в iOS необходимо "true" в enableHighAccuracy ).
У меня также было много проблем с возможностью определения местоположения, и я решил ее следующим образом:
создать api.provider и внедрить в компонент:
Объявление опций -geo:
private geoOptions: GeolocationOptions = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 12000
};
-onInit вызывается из конструктора:
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);
});
});
}
-конструктора, который уже обрабатывает getCurrentPosition ошибки и изменяет параметры точности для обратного вызова перед выполнением 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 упакованный метод:
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); }};
});
}
-и наконец, метод watchPosition :
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 Создайте ReplaySubject для хранения последних правильных значений координат.Он не всегда возвращается успешно, поэтому рекомендуется искать последние успехи и возвращать их вашему подписчику, если текущие не удаются.
Например:
public currentLocation = new ReplaySubject<Geoposition>(2);
Благо тебе тоже!