Background Geolocation in Ionic 2

Adding Background Geolocation to an Ionic 2 & 3 Application



·

In a previous tutorial, I have demonstrated how to use Geolocation in an Ionic 2 application. The method used in that tutorial is the “standard” way to use the Geolocation plugin, it will allow you to grab the users current position, or watch their position over time whilst they have the app open.

That is useful in a lot of circumstances, but you may want to access the devices GPS over a long period of time, including when the user closes your application. When using the standard Geolocation plugin, as soon as the user exits the application you lose your ability to track them.

This is a problem I have faced before, and it popped its head up again recently since I am currently building an Ionic 2 application that tracks how far a user has run, and I don’t expect the user to keep the app open the entire time they are running (which would be pretty awkward).

In this tutorial I am going to show you how you can enable Background Geolocation in your Ionic 2 applications. This means that you will be able to continue tracking a user’s location, and executing code in your application, even when the user closes your application. The application we are building will look like this:

Background Geolocation

Before We Get Started

Last updated for Ionic 3.7.1

Before you go through this tutorial, you should have at least a basic understanding of Ionic concepts. You must also already have Ionic set up on your machine.

If you’re not familiar with Ionic already, I’d recommend reading my Ionic 2 Beginners Guide first to get up and running and understand the basic concepts. If you want a much more detailed guide for learning Ionic, then take a look at Building Mobile Apps with Ionic.

1. Generate a New Ionic 2 Project

First, we will generate a new Ionic 2 project by running the following command:

ionic start ionic2-background-geolocation blank

We are also going to be creating a provider to handle the Geolocation, so once the app has finished generating, first run the following command:

cd ionic2-background-geolocation

to make the project your working directory, and then run:

ionic g provider LocationTracker

to generate a new provider. We will also need to add this new provider to the app.module.ts file.

Modify src/app/app.module.ts to reflect the following:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { LocationTracker } from '../providers/location-tracker';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    LocationTracker,
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

2. Install the Required Plugins

We will be using both the standard Geolocation plugin in this tutorial, as well as this background geolocation plugin. To install these you will need to run the following commands:

ionic plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation
ionic plugin add cordova-plugin-mauron85-background-geolocation
npm install --save @ionic-native/background-geolocation

You will also need to add these to the app.module.ts file.

Modify src/app/app.module.ts to reflect the following:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { LocationTracker } from '../providers/location-tracker';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { Geolocation } from '@ionic-native/geolocation';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    LocationTracker,
    BackgroundGeolocation,
    Geolocation,
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

3. Create the Location Tracker

We’re going to implement our Location Tracker provider now. We want this service to allow us to track a user’s location, and we also want the ability to stop tracking the user.

Let’s start out with a basic template for the provider, and slowly build some functionality into it.

Modify src/providers/location-tracker.ts to reflect the following:

import { Injectable, NgZone } from '@angular/core';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { Geolocation, Geoposition } from '@ionic-native/geolocation';
import 'rxjs/add/operator/filter';

@Injectable()
export class LocationTracker {

  public watch: any;    
  public lat: number = 0;
  public lng: number = 0;

  constructor(public zone: NgZone) {

  }

  startTracking() {

  }

  stopTracking() {


  }

}

We’ve imported both the Geolocation and BackgroundGeolocation plugins from Ionic Native, but you will notice that we have also imported Geoposition. This describes the type of the data that the Geolocation plugin returns, and will help us avoid issues with the TypeScript compiler.

We will be making use of NgZone in this tutorial, which allows us to force code to run inside of Angular’s zone. If you would like to know more about zones in Angular 2, I recommend reading Understanding Zones and Change Detection in Ionic 2 & Angular 2. The reason we need to do this is because, in the case of the plugin we are using, location changes don’t run inside of Angular’s zone, and thus they do not trigger change detection and our layout won’t update with the correct values. Using NgZone is not usually required.

We import the filter operator, which we will use to filter out certain data from the observable Geolocation returns us later, and we set up some member variables to hold some data. We’ve also set up two additional functions that we will finish implementing now.

Modify the startTracking() function to reflect the following:

  startTracking() {

    // Background Tracking

    let config = {
      desiredAccuracy: 0,
      stationaryRadius: 20,
      distanceFilter: 10, 
      debug: true,
      interval: 2000 
    };

    this.backgroundGeolocation.configure(config).subscribe((location) => {

      console.log('BackgroundGeolocation:  ' + location.latitude + ',' + location.longitude);

      // Run update inside of Angular's zone
      this.zone.run(() => {
        this.lat = location.latitude;
        this.lng = location.longitude;
      });

    }, (err) => {

      console.log(err);

    });

    // Turn ON the background-geolocation system.
    this.backgroundGeolocation.start();


    // Foreground Tracking

  let options = {
    frequency: 3000, 
    enableHighAccuracy: true
  };

  this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {

    console.log(position);

    // Run update inside of Angular's zone
    this.zone.run(() => {
      this.lat = position.coords.latitude;
      this.lng = position.coords.longitude;
    });

  });

  }

This function allows us to start tracking the user’s location. You will notice we have two distinct sections of code here: Foreground Tracking and Background Tracking. The “Foreground Tracking” code handles tracking the user whilst they have the open and just uses the standard watchPosition function the Geolocation plugin provides. The “Background Tracking” code handles tracking the user when the app is in the background and uses the background Geolocation plugin instead.

There’s actually quite a lot to the background geolocation plugin and I’d recommend reading up on the documentation, but the configuration options we have supplied here control when the application will be notified of the user’s position and how accurate it should be. The plugin has been optimised to take it easy on the user’s battery, but in general: the more accurate you want the data to be, the more battery power it is going to use.

The code for handling standard Geolocation updates looks a little strange. The watchPosition function returns an observable, which we can subscribe to in order to handle updates from it, but we can also filter an observable first if we like. This will get rid of any updates that we do not want, and in this case, we are filtering out any updates that return an error. We also assign a type of Geoposition to the data the observable emits, so that we don’t run into any issues with the TypeScript compiler when accessing the latitude and longitude properties on the position object.

In both cases, whenever we get an update we update the lat and lng member variables, and we force this to run inside of Angular’s zone so that it triggers change detection.

Also, note that we have set the debug option to true for the background geolocation, this means that the app will use local notifications to notify you whenever a background geolocation update occurs (handy for debugging!).

IMPORTANT: Whilst the standard Geolocation plugin can actually run through the browser, the background geolocation plugin can not. You must install the application on a device or emulator before being able to test this functionality. If you try to run it through a browser you will just receive errors.

Modify the stopTracking function to reflect the following:

  stopTracking() {

    console.log('stopTracking');

    this.backgroundGeolocation.finish();
    this.watch.unsubscribe();

  }

This is actually a pretty simple function. We call the finish method for the background geolocation plugin to stop tracking the user, and by simply unsubscribing from the watch observable it will cancel tracking the user with watchPosition.

4. Use the Location Tracker

Now that we have our fancy schmancy location tracker built, we just need to make use of it. To do that we are just going to add a simple implementation to our home page.

Modify src/pages/home/home.ts to reflect the following:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LocationTracker } from '../../providers/location-tracker';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public locationTracker: LocationTracker) {

  }

  start(){
    this.locationTracker.startTracking();
  }

  stop(){
    this.locationTracker.stopTracking();
  }

}

We’ve imported the location tracker here and injected it into our constructor so that we can use it throughout the class. We’ve also added two simple functions here to start and stop tracking.

The start function calls the startTracking function we added to the location tracker and the stop function calls the stopTracking function in the location tracker to stop tracking the users location. Now we just need to modify the home template so that we can call the two functions we just created.

Modify src/pages/home/home.html to reflect the following:

<ion-header>
  <ion-navbar color="secondary">
    <ion-title>
      Location Tracker
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <h3>Current Latitude: {{locationTracker.lat}}</h3>
  <h3>Current Longitude: {{locationTracker.lng}}</h3>
  <button ion-button full primary (click)="start()">Start Tracking</button>
  <button ion-button full primary (click)="stop()">Stop Tracking</button>
</ion-content>

Now you should be able to hit ‘Start Tracking’ and watch the position values update in your app, and the values will continue to update whether the app is in the foreground or in the background!

Background Geolocation

Summary

The ability to track a user’s location and continue doing stuff whilst your application is in the background opens up a big range of options when using Geolocation. Hopefully, this tutorial also highlights how creating providers in Ionic 2 can help modularise your code and allow you to simplify the use of more complex functionality – now that we’ve created this provider we can easily track the user’s location, background or not, simply by calling a single function.

What to watch next...

  • Marcos Alois Oliva

    do you have a similar tutorial for the previous version of Ionic ?

  • Hazou Shebly

    tried but i found few bugs

    1. the output returned in console

    ll enableProdMode() to enable the production mode.

    1 859127 log DEVICE READY FIRED AFTER, 873, ms

    2 868238 log [object Object]

    3 875804 log [object Object]

    4 888030 log [object Object]

    2. when clicking stop tracking

    6 890658 error EXCEPTION: Error during evaluation of “click”

    7 890659 error ORIGINAL EXCEPTION: TypeError: this.watch.unsubscribe is not a function

    8 890660 error ORIGINAL STACKTRACE:

    9 890661 error TypeError: this.watch.unsubscribe is not a function

    at LocationTracker.stopTracking (http://192.168.1.153:8100/build/js/app.bundle.js:172:18)

    at HomePage.stop (http://192.168.1.153:8100/build/js/app.bundle.js:92:20)

    at AbstractChangeDetector.ChangeDetector_HomePage_0.handleEventInternal (viewFactory_HomePage:103:23)

    at AbstractChangeDetector.handleEvent (http://192.168.1.153:8100/build/js/app.bundle.js:12950:29)

    at AppView.triggerEventHandlers (http://192.168.1.153:8100/build/js/app.bundle.js:22779:36)

    at eval (viewFactory_HomePage:336:104)

    at http://192.168.1.153:8100/build/js/app.bundle.js:31289:36

    at http://192.168.1.153:8100/build/js/app.bundle.js:31367:86

    at ZoneDelegate.invoke (http://192.168.1.153:8100/build/js/angular2-polyfills.js:390:29)

    at Object.NgZoneImpl.inner.inner.fork.onInvoke (http://192.168.1.153:8100/build/js/app.bundle.js:27213:41)

    10 890662 error ERROR CONTEXT:

    11 890664 groupEnd

    12 890669 error Uncaught EXCEPTION: Error during evaluation of “click”

    ORIGINAL EXCEPTION: TypeError: this.watch.unsubscribe is not a function

    ORIGINAL STACKTRACE:

    TypeError: this.watch.unsubscribe is not a function

    at LocationTracker.stopTracking (http://192.168.1.153:8100/build/js/app.bundle.js:172:18)

    at HomePage.stop (http://192.168.1.153:8100/build/js/app.bundle.js:92:20)

    at AbstractChangeDetector.ChangeDetector_HomePage_0.handleEventInternal (viewFactory_HomePage:103:23)

    at AbstractChangeDetector.handleEvent (http://192.168.1.153:8100/build/js/app.bundle.js:12950:29)

    at AppView.triggerEventHandlers (http://192.168.1.153:8100/build/js/app.bundle.js:22779:36)

    at eval (viewFactory_HomePage:336:104)

    at http://192.168.1.153:8100/build/js/app.bundle.js:31289:36

    at http://192.168.1.153:8100/build/js/app.bundle.js:31367:86

    at ZoneDelegate.invoke (http://192.168.1.153:8100/build/js/angular2-polyfills.js:390:29)

    at Object.NgZoneImpl.inner.inner.fork.onInvoke (http://192.168.1.153:8100/build/js/app.bundle.js:27213:41)

    ERROR CONTEXT:

    [object Object], http://192.168.1.153:8100/build/js/angular2-polyfills.js, Line: 324

    • Runfast Webmaster

      Hi,
      It seems the background geolocation is not working when the user turn off the app.
      What did I miss ??

      Thanks for this greet tutorial.

      • Cristian Baez

        Hello, try to add into backgroundGeolocationConfig the parameter “stopOnTerminate: false” (defaults to true).

        let config = {
        desiredAccuracy: 0,
        stationaryRadius: 20,
        distanceFilter: 10,
        debug: true, // enable this hear sounds for background-geolocation life-cycle
        stopOnTerminate: false, // enable this to clear background location settings when the app terminates
        interval: 2000
        };

  • Keith Mattix

    When I try to use backgroundGeoLocation, ionic says it’s undefined.

    • Ventis

      Yeah, exactly the same experience on typescript. Did you get it solved? Perhaps Josh can help here.

      • Keith Mattix

        Well, first of all, I was trying to implement geofencing manually when there’s actually a simple cordova plugin for it: https://github.com/cowbell/cordova-plugin-geofence/
        Second of all, I realized that even though typescript may complain, the app will still work. At least, that’s what Josh said in Slack.

      • Ventis

        I really dont think so. Or perhaps its no longer so. backgroundGeoLocation gives error that prevents ionic 2 apps from beta 8 not to build/compile unless you comment it out. And once you do, it does not work anymore. I think it is the plugin cordova-plugin-mauron85-background-geolocation that may be the issue. Can anyone with a success try, help us here.

      • Ventis

        Again i tried this after reading the new Ionic documentation http://ionicframework.com/docs/v2/native/backgroundgeolocation/ and i used ionic-angular’s BackGroundLocation and it compiled very well. Though i havenot been able to test it using a device. But when i debug i was only able to get the gps location once. You may also wish to try.

      • Galaxy Lam

        I have import { BackgroundGeolocation } from ‘ionic-native’; however, I still got the [ts] error “can’t find name backgroundGeoLocation”, also “this.watch” has [ts] error too stated property ‘watch’ doesn’t exist. May anyone help on typescript version? Many thanks.

      • Ventis

        Check the package.json file and let me know the version of ionic-native. I had to change the version manually to 1.3.8 or upper to make it work.

      • Emmanuel Bédard

        On the location-tracker.ts file (the providers), use a capital B when you call BackgroundGeolocation.

        BackgroundGeolocation.configure(backgroundOptions).then((location) => {
        this.notifyLocation(location);
        }).catch((err) => {
        console.log(‘BackgroundGeolocation error’);
        });

        BackgroundGeolocation.start();

    • Arturo Torres Sánchez

      Don’t know if you still need this, but the solution was to declare both backgroundGeolocation and geolocation in the constructor, next to ngZone

  • Hi, thank you for your time and help with this. I am having two issues:
    1. this.watch.unsubscribe(); in stopTracking is not working as expected: unsubscribe is not part of the object?
    2. When my app is in background, I am trying to log my current position (console.log(position);), but its not working. Its working only when I open the app…any help, please? Thank you again.

  • Ventis

    Can anyone provide the steps to replicate this concept in ionic 2 typescript .ts instead of the .js I tried adding the provider ‘ionic g provider LocationTracker –ts’ it did work but other modules like startTracking, stopTracking, etc were not part of the result unlike the js default.

    Thanks

  • Aish App

    Thats a great tutorial. I tried this but when i open some application or close my application, background geolocation is not working. Please help me.

  • John D. Barros Puccini

    Has anyone tried this with ionic RC.0? What changes have to be done? Thanks

  • Hey everyone, I’ve just updated this tutorial to RC.0

    • John D. Barros Puccini

      Thank you!

    • Ventis

      Many thanks and well done to your good job.

    • Vinícius Secco

      Hi Josh, how are you?
      I still using beta 11, can you help me?
      In provider:
      1º Geoposition not found
      2º in BackgroundGeolocation.configure((location) => {

      console.log(‘BackgroundGeolocation: ‘ + location.latitude + ‘,’ + location.longitude);

      find this error: [ts] Argument of type ‘(location: any) => void’ is not assignable to parameter of type ‘Config’.
      Property ‘desiredAccuracy’ is missing in type ‘(location: any) => void’.

  • Something weird is happening in my HTC 626s, in the first 10 or 15 seconds is appearing a Toast with some strange information also making some sounds.

  • armando

    I have a problem with build my app, error Android…. somebody app worked this app?

  • Yasir Aziz

    @joshmorony:disqus Can you please provide any example or sample project for Ionic V1, I’m having trouble while integrating it with V1.

  • Chris Scutt

    Thanks for the great tutorial. Have it working in a Ionic2 Rc 2 app. Am getting a toast with accuracy and other random info which makes beeping noises! Any ideas on how to disable this toast? Must be coming from plugin?any help would be appreciated!

    • Karan sharma

      Did you get any solution of it? Cz I am getting it too

  • hong

    hi josh, that’s a greate tutorial. but background geolocation is not working. Please help me.

  • dnez

    Hi

    I managed to get the location and display on browser by using ionic serve.

    However, I build the app and launched on my android device. It doesn’t display any lat, long after start tracking. Background tracking is enabled though.

    May I know what did I miss?

    • Alan Young

      Yes I’ve got the same issue.

      I can get the Foreground tracking to work in a browser vie ionic serve but nothing happens through an emulator or on a physical device when I click “Start Tracking”. Anyone have any ideas??

      Cheers,

    • Pierre-André Seeyoucloud

      Same problem here. It works fine on iOS, but on Android, it doesn’t work : neither on an emulator nor an a real device. The tracking seems to be well enabled though.
      My device is running on Marshmallow (Nexus 5, 2013)

  • José Rogério Ferreira Dos Sant

    Wonderful this article, very good.
    In my tests, I changed a ‘frequency’ option to ‘timeout’ option, described in the function documentation.
    Congratulations by the text.

  • Rodrigo Rubio

    Awesome tutorial, thank you! just a quick one. I’m assuming on “startTracking” is where i could send the location to my server?

  • Laxman G

    If application is in background state, this code is not working…
    Please suggest me how to solve.

  • Fernando Saez

    Hi @joshmorony:disqus I added “if (this.platform.is(‘ios’) || this.platform.is(‘android’)) ” to the block of background geolocation to avoid errors in the browser. I have a question that I can test now. In the foreground the two plugins are running at the same time?
    Thanks

  • Clément de Bellefroid

    Hello,
    Thanks for the turorial, everything is working fine except one thing:
    You are specifying a frequency variable for the Foreground tracking, but the location isn’t updating according to this variable.
    In this post http://stackoverflow.com/questions/35294154/cordova-geolocation-watchposition-frequency-is-higher-than-the-options-allow-it
    the person says that it is not possible to change the frequency using Geolocation plugin and gives another method using dates to achieve this.
    Could you provide us with an example combining your way of doing things and his ?

  • Hi Josh,
    Thanks for article, background-geolocation has an option to send data to server, it’s not well documented that what would be the JSON object in post request, do you know what is the format of data?

  • Krishna Kumar

    Hey Josh,
    I’ve been seeing a lot of tutorials and learning ionic 2. You’re simply awesome. The way your article is put up along with explanations.. Just a fabulous work!! Keep going hard.
    I have a query. How can I pass the location data running in service to my page.ts to update my marker?
    I tried including your startTracking method directly in the page.ts file. But I’m not sure if it’s a good pattern to listen for location updates directly on pages.
    Any explanation on this would be much appreciated. Thanks a ton once again!

    • mark

      Im also interested on this Kishna, have you managed to solve it without moving the startTracking method? Im trying to do this with observables but cant make it work.

  • abhijeet kushwaha

    Hi Josh many thanks for the awesome explanation, both the plugins are working fine for me i am able to post the coordinates to server as well.
    My question is can i somehow configure the background geolocation plugin to run in foreground as well because here https://github.com/mauron85/cordova-plugin-background-geolocation they have mentioned that plugin can be used for foreground as well as background.

    Many thanks for the awesome work again

  • Foued

    How can i retrieve street, city, country ?

  • bionicbrad

    I’m pretty sure that the .finish() method is only for iOS, and only needs to be called in the callback in .configure() that receives the location update. You have to detect that you are on iOS, and ensure that .finish() is called to make sure the app doesn’t keep running too long in the background (paraphrasing from the cordova plugin’s docs). If you call the .finish() method on a non-ios platform, it will cause an error.

    To stop tracking, call BackgroundGeolocation.stop() – at least, that seems to be the way it works for me.

    Has anyone else encountered the same?

    • Guillaume Bartolini

      Yes i did… But what is “too long” ? And what is the point off background geolocation if it’s only for few seconds/ minutes? maybe i am missing something….

  • alain

    thanks for the tuto. i’m getting the following error with ionic 2 & ts:

    when i press stop button :

    Error: Uncaught (in promise): Invalid action
    at s (polyfills.js:3)
    at polyfills.js:3
    at Object.callbackFromNative (cordova.js:295)
    at processMessage (cordova.js:1119)
    at processMessages (cordova.js:1142)
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (main.js:36094)
    at t.invoke (polyfills.js:3)
    at e.run (polyfills.js:3)
    at polyfills.js:3
    ErrorHandler.handleError @ main.js:52180
    next @ main.js:33784
    schedulerFn @ main.js:35294
    SafeSubscriber.__tryOrUnsub @ main.js:29085
    SafeSubscriber.next @ main.js:29034
    Subscriber._next @ main.js:28987
    Subscriber.next @ main.js:28951
    Subject.next @ main.js:19498
    EventEmitter.emit @ main.js:35286
    NgZone.triggerError @ main.js:36136
    onHandleError @ main.js:36115
    t.handleError @ polyfills.js:3
    e.runGuarded @ polyfills.js:3
    r @ polyfills.js:3
    i @ polyfills.js:3

  • i’ve tested this code with ionic 2.0 release but does’nt work..
    do you have updated version ?

  • George Chapman

    Hi,

    I have just followed this tutorial word for word and receive the following error:

    Property ‘filter’ does not exist on type ‘Observable’.
    L56: this.watch = Geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((posi

    This is using
    “ionic-angular”: “2.0.0”
    and
    “@ionic/app-scripts”: “1.0.0”
    which i believe is where the issue is arising.

    Any ideas?
    Thanks

    PS using:
    “ionic-angular”: “2.0.0-rc.3”
    and
    “@ionic/app-scripts”: “0.0.45”
    works just fine.

    • Dawn Wilkins

      Add import ‘rxjs/add/operator/filter’; to location-tracker.ts

  • Mishal Alshuwaikhat

    Great effort. Many thanks!

  • Sherwin De Jesus

    I have added a googleMap on my home page. i want to pan the map to the current users location using the solution above. how would i do that?

  • Barry Gribben

    Hi Josh, very clear and helpful, and i am enjoying your other material too! Foreground works fine in android and iOS. I have wired up to a db no prob too – great. But Background service doesn’t seem to fire. Data starts streaming in again when i bring to foreground. I get “error “start” promise ignored” when I hover over “start”. But I realise the callback is set in the configure call. Have I done something wrong that is obvious do you think? Seesm similar issue being reported below too…

  • Chris Scutt

    This was working great for me until this evening. I have just about finished a geotracking app using this and accidently updated ionic-native or something while adding the camera. I am not getting the following:

    typescript /src/providers/location-tracker.ts, line: 29
    Supplied parameters do not match any signature of call target.

    L29: BackgroundGeolocation.configure((location) => {

    I haven’t changed anything to do with the location services. I then tried to build the tutorial about from scratch and get an error saying can’t find Geoposition. I am sure I have messed up the plugins. I removed Geolocation and Background Geolocation and reinstalled but error now persists. Any ideas?!!! Have there been breaking changes in the last few days?

    • Chris Scutt

      I have discovered the problem seems to be with ionic-native. The upgraded version throws an error. I uninstalled and installed version 2.4.1 and the app started working again.

    • ahmed rami

      Chris Scutt , Could you pleasse provide the code , i have try again , “Geoposition is not knwon ” .

      ionic version :2.2.1 , node version :6.10.0 , cordova version:6.5.0

  • ahmed rami

    it was an error in the location-tracker.ts : [ts] Cannot find name ‘Geoposition’. i have already insatalled the plugin as mentionned

    • Fernando Gomes

      Hi, me too, I’m getting this error also:

      typescript: C:/Work/PhoneGap/ionic2-background-geolocation/src/providers/location-tracker.ts, line: 55
      Cannot find name ‘Geoposition’.

      Any idea of what the problem is? The symbol is imported at the beggining of the file:

      import { Geolocation, Geoposition, BackgroundGeolocation } from ‘ionic-native’;

      Thanks!

      Fernando

  • Anton

    Josh Morony, good day ! Could you suggest please .. is it possible use this plugin just for prevent app sleep in background or locked ? Not stopped processed data(insert,update to the db).

  • Hudhud

    It says that the properties “backgroundGeolocation” and “geolocation” don’t exist on type “LocationTracker”. I’ve also tried with capital B/G, but then it says that the next thing (after “.”) doesn’t exit in the type. What have I done wrong?

  • Chente Dávila

    I have a question … If the application senses in the background geographic location. Why the application does not continue to get the current geographical position when switching applications, for example whatsapp. Do I have to open the Application to get information about my position?

  • Larry Parks

    Hey Josh. Thanks for the tutorial. I’m making a bike app and this is exactly what I needed.

    The tutorial is a little confusing to the less experienced because it does not show what the constructor should look like in the end. In addition to public ngZone: NgZone, there also needs to be public backgroundGeolocation: BackgroundGeolocation, public geolocation: Geolocation in order for your snippets to work seemlessly. Keep up the good work!

  • Himanshu Dash

    Typescript Error
    Property ‘backgroundGeolocation’ does not exist on type ‘LocationTracker’.
    This error is coming after the setup and unable to build the project

    • balakrishna

      @himanshudash:disqus did you solve it ? I am getting the same error.

  • balakrishna

    I have solved this problem.,”Property ‘backgroundGeolocation’ does not exist on type ‘LocationTracker’.”

    import ‘rxjs/add/operator/filter’;
    import { BackgroundGeolocation,BackgroundGeolocationConfig } from ‘@ionic-native/background-geolocation’;
    import { Geolocation, Geoposition } from ‘@ionic-native/geolocation’;

    constructor(public zone: NgZone,private backgroundGeolocation: BackgroundGeolocation,private geolocation: Geolocation) {};
    const config: BackgroundGeolocationConfig = {};

  • SarahCarroll123

    I am getting the run time error “Cannot read property ‘lat’ of undefined” anyone have any ideas?

  • valmy roi

    Only shows “Background Tracking ENABLED” on my phone’status bar without latitude nor longitude changing

  • Robby alj

    i want to use this in my user app,,, but how can i insert value update current position automaticaly into database

  • fansz

    HI josh , it’s possible to have acces to the zone in the home.ts ? i try in home.ts that : this.locationTracker.lat but it’s undefined

  • I need to check if a user is inside or outside an area (area can be a circle with lat & lng for center point plus a radius)
    Which is the best approach ?
    Background Geolocation like this article describe ?
    Thanks

  • Shane

    To anyone implementing this today, make sure to read through http://ionicframework.com/docs/native/background-geolocation/ as there are a few things that don’t work.

    Mainly, use this.backgroundGeolocation.stop(); in the stop method. this.backgroundGeolocation.finish(); belongs at the end of the subscribe, and is meant for ios only.

  • Kavan Mannapperuma

    Does anyone know the difference between background tracking shown here and the cordova ‘geolocation.watchposition’? Why can’t geolocation.watchposition be used instead of background tracking?

  • Abhishek Pandya

    Keep doing nice work man….

  • Abhishek Pandya

    Does anyone have demo of this?

  • Pyungdoo Jeong

    is it really working? I don’t think so….on location-tracker.ts ‘s this.waht=this … callback, I put function to store in firebase, but not working. only save date when ionic is active.

  • Raji Philip

    Hello Josh, i followed the instructions and it worked fine in my browser but for android device i need to restart the device for it to work and if i close the application and open it the geolocation wont work again. is there any way out.

    • Cristian Baez

      Hello, try to add into backgroundGeolocationConfig, the parameter stopOnTerminate: false (defaults to true).

      let config = {
      desiredAccuracy: 0,
      stationaryRadius: 20,
      distanceFilter: 10,
      debug: true, // enable this hear sounds for background-geolocation life-cycle
      stopOnTerminate: false, // enable this to clear background location settings when the app terminates
      interval: 2000
      };

  • Anna

    Hi, the BackgroundGeolocation by itself should work on both foreground, background as described on https://ionicframework.com/docs/native/background-geolocation. Do we need still Geolocation standard plugin to track foreground?

  • Hi, excellent tutorial, it all works great. Question: How can I watch position changes in background mode? In foreground you can do it the geolocation.watchPosition. But, if I want to do some action (i.e: send a local notification) when my position changes in the background how can I do it? Do I have to create an observable myself? Ideas? Thanks!!

  • Abhimanyu Kumar

    I m getting android build error

    :processDebugResources
    /Volumes/data/projects/docmed/platforms/android/build/intermediates/res/merged/debug/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr ‘android:keyboardNavigationCluster’.

    /Volumes/data/projects/docmed/platforms/android/build/intermediates/res/merged/debug/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr ‘android:keyboardNavigationCluster’.

    FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ‘:processDebugResources’.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

    * Try:
    Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output.

    BUILD FAILED

    Total time: 12.903 secs
    Error: /Volumes/data/projects/docmed/platforms/android/gradlew: Command failed with exit code 1 Error output:
    Note: Some input files use or override a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    Note: Some input files use or override a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    /Volumes/data/projects/docmed/platforms/android/build/intermediates/res/merged/debug/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr ‘android:keyboardNavigationCluster’.

    /Volumes/data/projects/docmed/platforms/android/build/intermediates/res/merged/debug/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr ‘android:keyboardNavigationCluster’.

  • Johannes Schmitt

    To all Android devs: Try the “this.backgroundGeolocation.stop();” instead of “this.backgroundGeolocation.finish();” <- This is mandatory for iOS Devices.
    The above avoids the 'Uncaught in Promise (Invalid action)' Error.

  • Samuel Prabhu D

    In Ionic 3, how to post the locations from background geolocation to restapi with some custom data such as date, username, uuid, time?

  • ema

    Hello,
    using the plugin as above in congiunction with FCM Plugin, fails to compile in android:
    * What went wrong:
    Execution failed for task ‘:processDebugGoogleServices’.
    > Please fix the version conflict either by updating the version of the google-services plugin (information
    about the latest version is available at
    https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of
    com.google.android.gms to 9.0.0.

    Anyone have suggestions for me?

  • Abhimanyu Kumar

    my app stuck on splash screen
    and last log is

    LocationManager didChangeAuthorizationStatus 0

  • Seoung Kwang Kim

    When I deploy my iPhone, it show bule banner (myapp is Actively Using Your Location) on the top screen. how can i disable it?