Ionic4: Not getting location if we minimize the app

463 Views Asked by At

I am using Ionic4

Developing software that has to fetch the user's mobile location in both foreground and background mode.

  1. I have used ionic 4 background mode to enable the app to run in background.
  2. Using geolocation to fetch the mobile location.

This geolocation.getCurrentPosition is working fine in foreground but not in background. But it returns value when we resume the app again.

I have tried a lot of ways to solve this issue but still it is giving the same. Can anyone help me solve this issue? Thanks in advance.

var options: PositionOptions = { enableHighAccuracy: true };

    this.geolocation.getCurrentPosition(options).then(res => {
      this.zone.run(() => {
        console.log('Get current position Success = ', res);
        this.getCurrentPosistion();
        // this.updateLocationInDatabase(location.coords);
      });
    }).catch(err => {
      console.error('Error occurred = ', err);
      this.getCurrentPosistion();
    });
1

There are 1 best solutions below

0
On

You can also use getCurrentLocation with watchposition because watchposition tracking location.

this.geolocation.getCurrentPosition().then((resp) => {

// resp.coords.latitude

// resp.coords.longitude

}).catch((error) => {

console.log('Error getting location', error);

});

let watch = this.geolocation.watchPosition();

watch.subscribe((data) => {

// data can be a set of coordinates, or an error (if an error occurred).

// data.coords.latitude

// data.coords.longitude

});

Otherwise use Plugin

https://ionicframework.com/docs/v3/native/background-geolocation/