Search code examples
cordovaionic-frameworkgeolocationionic2cordova-plugins

ionic 2 Geolocation clearWatch or unsubscribe


So I'm working with Google Maps and Ionic 2. Cordova has a plugin for retrieving user's geolocation, and I have two questions about the plugin.

But before I state my questions, here's my code

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, there are two ways to stop watching the user's location: watch.unsubscribe() and Geolocation.clearWatch(watch). However, I have no clue what's the difference besides unsubscribe has the type of Observable and the other is imported from the Geolocation plugin. Which one should I use?

  2. The above question is actually trivial, the most importent problem I have now is that neither of them works. watch.unsubscribe() give the error that [ts] Property 'unsubscribe' does not exist on type 'Observable<Geoposition>'. and Geolocation.clearWatch(watch) gives me [ts] Property 'clearWatch' does not exist on type 'typeof Geolocation'. Is there something I'm missing?


Solution

  • If you look at the Ionic Native Typescript wrapper for the geolocation plugin, you can see that:

    • it does not expose the clearWatch() function directly
    • its watchPosition() wrapper returns an Observable whose unsubscribe() action is to call clearWatch() on the geolocation plugin with the internal watchId. Hence the Ionic Native way to clear the watch is to call unsubscribe() on the Observable returned by Geolocation.watchPosition().

    However, if for some reason that's not working, you could just call the plugin API directly:

    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);