离子2地理定位clearWatch或取消订阅

时间:2017-03-23 07:05:02

标签: cordova ionic-framework geolocation ionic2 cordova-plugins

所以我正在使用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);
    });
}
  1. AFAIK,有两种方法可以停止观看用户的位置:watch.unsubscribe()Geolocation.clearWatch(watch)。但是,我不知道除了unsubscribe类型Observable以及另一个是从Geolocation插件导入之外还有什么区别。我应该使用哪一个?

  2. 上述问题实际上是微不足道的,我现在最重要的问题是它们都不起作用。 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'.我是否遗漏了某些内容?

2 个答案:

答案 0 :(得分:1)

如果您查看Ionic Native Typescript wrappergeolocation plugin,就可以看到:

  • 它不会直接公开clearWatch()功能
  • its 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)

即使来晚了...

  • watchPosition()返回一个Observable
  • 您可以订阅此Observable
  • subscribe()调用返回一个订阅
  • 从订阅中,您可以取消订阅()

将它们放在一起:

let subscription = this.geolocation.watchPosition().subscribe(
    (position) => { ... },
);

...

subscription.unsubscribe();