question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to prevent multiple watchLocation listeners ?

See original GitHub issue

Hi,

Is there some option to stop all active watchLocation listeners started from the app ?

In my case I have component which starts watchLocation listener every time when is visited. The problem is the previous listeners don’t stop to listen for gps location ( and i have multiple active listeners for gps location ).

How can i stop them without to know their watch IDs ?

I tried with simple check :

               if ( !this.watchId ) {
                    this.watchId = geolocation.watchLocation(this.locationReceived, this.error, {
                        desiredAccuracy: 20,
                        updateDistance: 0,
                        minimumUpdateTime: 15000,
                        maximumAge: 6000
                    });
                }

But every time this watchID is different for each new visit in the component and accordingly it`s not created ( this doesn’t work ) .

Thanks for help !

Issue Analytics

  • State:open
  • Created 7 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
briandilleycommented, Sep 23, 2018

@devyaz - no

On Sat, Sep 22, 2018, 2:16 AM devyaz notifications@github.com wrote:

@briandilley https://github.com/briandilley how about a vanilla js example

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/NativeScript/nativescript-geolocation/issues/46#issuecomment-423729747, or mute the thread https://github.com/notifications/unsubscribe-auth/ABBNz4Nun_9ZcB8lz0lMQQJ34ezeACR1ks5udgAHgaJpZM4LZP2f .

1reaction
briandilleycommented, Dec 28, 2017

here:

import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Subscription} from "rxjs/Subscription";
import {interval} from 'rxjs/observable/interval'
import {timer} from 'rxjs/observable/timer'
import {delayWhen, distinctUntilChanged, flatMap, map, retryWhen, share, switchMap, tap} from 'rxjs/operators'

import {clearWatch, enableLocationRequest, Location as GPSLocation, watchLocation} from "nativescript-geolocation";
import {Accuracy} from "tns-core-modules/ui/enums";
import {Analytics} from "../utils/analytics";

export const DEFAULT_OPTIONS = {
  desiredAccuracy: Accuracy.high,
  minimumUpdateTime: 1000,
  iosAllowsBackgroundLocationUpdates: true
};

export {Location as GPSLocation} from "nativescript-geolocation";

@Injectable()
export class LocationService {

  private _lastLocation: GPSLocation;

  private locationEvents: Observable<GPSLocation>;

  public constructor() {
    this.locationEvents = this.askForLocationPermissions()
      .pipe(
        flatMap(() => new Observable((sub) => {
          let watchId = -1;
          try {
            watchId = watchLocation(
              (loc) => {
                this._lastLocation = loc;
                console.log(`NEW! lat: ${loc.latitude} lon: ${loc.longitude}`)
                sub.next(loc);
              },
              (error) => {
                sub.error(error);
              },
              DEFAULT_OPTIONS);
            console.info(`[watchLocation ${watchId}] Subscribed`);

          } catch(error) {
            sub.error(error);
          }

          return () => {
            if (watchId != -1) {
              console.info(`[watchLocation ${watchId}] Unsubscribed`);
              clearWatch(watchId);
            }
          };
        })),
        switchMap((loc: GPSLocation) => interval(1000)
          .pipe(
            map(() => loc),
            tap((loc) => console.log(`lat: ${loc.latitude} lon: ${loc.longitude}`)))),
        share());
  }

  public get lastLocation(): GPSLocation {
    return this._lastLocation;
  }

  /**
   * Keeps the location updated by calling the given callback, the
   * subscription is returned.
   */
  public keepLocationUpdated(callback: (loc: GPSLocation) => void): Subscription {
      return this.watchLocation()
        .pipe(
          retryWhen((errors) => errors
            .pipe(
              tap((error) => Analytics.logError(error, "Error in keepLocationUpdated, attempting retry in 1 second")),
              delayWhen(() => timer(1000)))),
          distinctUntilChanged((x, y) => x.latitude !== y.latitude || x.longitude !== y.longitude))
        .subscribe(
          (loc) => callback(loc),
          (error) => Analytics.logError(error, "Fatal error in keepLocationUpdated"));
  }

  /**
   * Begins watching the current location.
   */
  public watchLocation(): Observable<GPSLocation> {
    return this.locationEvents;
  }

  /**
   * Asks for location permissions, returns either true or an error.
   */
  public askForLocationPermissions(): Observable<boolean> {
    return new Observable((sub) => {
      enableLocationRequest()
        .then(() => {
          sub.next(true);
          sub.complete();
        })
        .catch(() => sub.error(new Error('Location services not enabled')));
    });
  }

}
Read more comments on GitHub >

github_iconTop Results From Across the Web

geolocation watchposition multiple locations? - Stack Overflow
I got it solved, the problem was that I was putting the listener event out of the marker object, so the marker variable...
Read more >
Geolocation API. As a web developer sooner or later… - Medium
watchPosition ( // the same as getCurrentPosition, but called multiple times );. Note: This method is basically event listener, so you can ...
Read more >
Geolocation clearWatch() seems not to stop GPS tracking
When i start checking geolocation with navigator.geolocation.watchPosition() (cordova-plugin-geolocation is installed), and want to stop it, ...
Read more >
Geolocation.watchPosition() - Web APIs | MDN
The Geolocation method watchPosition() method is used to register a handler function that will be called automatically each time the ...
Read more >
BackgroundGeolocation | React Native Background Geolocation
Interacting with the SDK is largely through implementing listeners on the ... the plugin requests multiple location samples in order to record the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found