所以我正在使用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);
});
}
AFAIK,有两种方法可以停止观看用户的位置: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'.
我是否遗漏了某些内容?
答案 0 :(得分:1)
如果您查看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);
答案 1 :(得分:1)
即使来晚了...
将它们放在一起:
let subscription = this.geolocation.watchPosition().subscribe(
(position) => { ... },
);
...
subscription.unsubscribe();