手机的行为也会因您的准确度而异(例如:在 iOS 中,必须在 enableHighAccuracy 中“true”)。
我在定位功能方面也遇到了很多问题,最终解决了下一个问题:
创建 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();
}
});
}
- 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);
});
});
}
-提示
创建一个 ReplaySubject 来存储最后一个正确的坐标值。它并不总是成功返回,因此建议搜索最新的成功并在当前失败时将它们返回给您的订阅者。
例如:
public currentLocation = new ReplaySubject<Geoposition>(2);
也祝福你!