所以我正在使用Google Maps和Ionic 2. Cordova有一个用于检索用户地理位置的插件,我对这个插件有两个问题。
但在我陈述我的问题之前,这是我的代码
import { Geolocation } from 'ionic-native';
watchPosition(marker) {
let watch = Geolocation.watchPosition({
//enableHighAccuracy: true
});
watch.subscribe((pos) => {
marker.setPosition({
lat: pos.coords.latitude,
lng: pos.coords.longitude
});
});
// stop watching if the user starts dragging the map
this.map.addListener('dragstart', () => {
// There might be two ways to do this, but non of them works
watch.unsubscribe();
Geolocation.clearWatch(watch);
});
}
watch.unsubscribe()
和Geolocation.clearWatch(watch)
。但是,我不知道除了unsubscribe
有Observable
类型和另一个是从Geolocation
插件导入的差异。我应该使用哪一个?watch.unsubscribe()
给出[ts] Property 'unsubscribe' does not exist on type 'Observable<Geoposition>'.
和Geolocation.clearWatch(watch)
给我的错误[ts] Property 'clearWatch' does not exist on type 'typeof Geolocation'.
有什么我缺少的吗?如果你看看Ionic Native Typescript wrapper的geolocation plugin,你可以看到:
clearWatch()
函数watchPosition()
wrapper返回一个Observable,其unsubscribe()
动作是在地理位置插件上用内部clearWatch()
调用watchId
。因此,清除手表的Ionic Native方法是在unsubscribe()
返回的Observable上调用Geolocation.watchPosition()
。但是,如果由于某些原因无效,您可以直接调用插件API:
declare var navigator: any;
// Add watch
let watchId = navigator.geolocation.watchPosition((position) => {
// do something with position
} , (error) => {
// do something with error
}), options);
// Clear watch
navigator.geolocation.clearWatch(watchId);
即使有点晚......
把它们放在一起:
let subscription = this.geolocation.watchPosition().subscribe(
(position) => { ... },
);
...
subscription.unsubscribe();