capacitor-community / background-geolocation

A Capacitor plugin that sends you geolocation updates, even while the app is in the background.
MIT License
180 stars 56 forks source link

Avoiding duplicate watchers #21

Closed gbrits closed 3 years ago

gbrits commented 3 years ago

Is it possible to specify an ID for a watcher so that if your code accidentally attempts a duplication of a background watcher it will overwrite an existing watcher or just not create a new one, since one already exists? Or have I missed features in the library that already exist? Thanks!

gbrits commented 3 years ago

Ok, was as simple as running it into a variable & wrapping that in an if statement. Sorry for the bother.

if(!that.clockedOnId) {
  that.clockedOnId = BackgroundGeolocation.addWatcher({
    id: 1337,
    backgroundMessage: "This will stop when you stop it",
    backgroundTitle: "Currently Tracking",
    requestPermissions: true,
    stale: false,
    distanceFilter: 100
  },
  (location, error) => {
    if (error) {
        if (error.code === "NOT_AUTHORIZED") {
            Modals.confirm({
                title: "Location Required",
                message: (
                    "This app needs your location, " +
                    "but does not have permission.\n\n" +
                    "Open settings now?"
                )
            }).then(function ({value}) {
                if (value) {
                    BackgroundGeolocation.openSettings();
                }
            });
        }
        return console.error(error);
    }
    that.logGPSCoordinate(location); // Or whatever function you want to run
    return console.log(location);
  });
  alert('Watcher executed with ID: '+that.clockedOnId);
} else {
  alert('[Avoided duplication] - Watcher already running...');
}