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

问题描述 投票:1回答:2

所以我正在使用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)。但是,我不知道除了unsubscribeObservable类型和另一个是从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'.有什么我缺少的吗?
cordova ionic-framework geolocation ionic2 cordova-plugins
2个回答
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
投票

即使有点晚......

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

把它们放在一起:

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

...

subscription.unsubscribe();
© www.soinside.com 2019 - 2024. All rights reserved.