Skip to content

[Bug]: Issue with Location Updates in Ionic Capacitor (Android & iOS) #315

Open
@nitish9625

Description

@nitish9625

Required Reading

  • Confirmed

Plugin Version

6.1.0

Cap Doctor

ionic cap build android

Mobile operating-system(s)

  • iOS
  • Android

Device Manufacturer(s) and Model(s)

oneplus, iphone 16

Device operating-systems(s)

ios 18, android 14

What happened?

I am using your plugins in my Ionic Capacitor project for both Android and iOS. While the initial location retrieval works correctly, I am experiencing an issue when the device is in motion. The location updates are not reflecting the current position; instead, the logged data often shows the previous location.

I have verified that location permissions are granted and that the necessary configurations are set up correctly. However, the issue persists. Could you please assist me in resolving this? Any guidance on ensuring accurate real-time location updates would be greatly appreciated.

Plugin Code and/or Config

async checkAndRequestPermission(){
    // Get current permission status
 const providerState = await BackgroundGeolocation.getProviderState();
 console.log("check permission", providerState);

 let locationStatus:string;
 if(providerState.status == 3){
   console.log("Permission changed to: 'Always Allow'");
   locationStatus = 'Always Allow';
 } else if(providerState.status == 2){
   console.log("Permission changed to: 'While Using the App'");
   locationStatus = 'While Using the App';
 }else{
   console.log("Permission changed to: 'Denied'");
   locationStatus = 'Denied';
 }
   let data ={
     "load_id":this.getStoredLoadId(),
     "location_permission":locationStatus

   }
   console.log("permission data", data);
   this.authService.sendFCMToken(data)
   .subscribe(res=>{
     console.log("load with device token",res);
   })

 // Check if "Always" permission is granted (iOS)
 if (!providerState.enabled || providerState.status !== BackgroundGeolocation.AUTHORIZATION_STATUS_ALWAYS) {
   // Request "Always" permission
   const status = await BackgroundGeolocation.requestPermission();
   // Check if permission was granted
   if (status === BackgroundGeolocation.AUTHORIZATION_STATUS_ALWAYS) {
     console.log("Always Allow permission granted ✅");
     await BackgroundGeolocation.start();
   } else {
     //alert("Background tracking requires 'Always Allow' permission. Please enable it in Settings.");
     //await App.openAppSettings() // Open app settings
   }
 } else {
   console.log("Always Allow permission already granted ✅");
   await BackgroundGeolocation.start();
 }

 // check what is the status
 BackgroundGeolocation.onAuthorization((status)=>{
  console.log("background location", status);
  if(status.status == 3){
    console.log("Permission changed to: 'Always Allow'");
  } else if(status.status == 2){
    console.log("Permission changed to: 'While Using the App'");
  }else{
    console.log("Permission changed to: 'Denied'");
  }
 })

 }

  // Initialize geolocation with persistent foreground service
 async initializeGeolocation() {
  this.checkAndRequestPermission();
    this.subscriptions.push(BackgroundGeolocation.onLocation((location)=>{
      this.addEvent('onLocation', location);
      if (location && location.coords) {
        const { latitude, longitude } = location.coords;
        const loadId = this.getStoredLoadId();
        const user = this.getUserDetails();
        BackgroundGeolocation.setConfig({
          params: {
            load: loadId, // Use the stored loadId
            latitude:String(latitude),
            longitude: String(longitude),
            user:user,
            device_details:JSON.stringify(location)
          }
        }).then(() => {
          console.log('Location params updated:', { latitude, longitude });
        }).catch((error) => {
          console.error('Error updating location params:', error);
        });
      }
    }));

    this.subscriptions.push(BackgroundGeolocation.onMotionChange((event)=>{
      this.addEvent('onMotionChange', event)
    }));

    this.subscriptions.push(BackgroundGeolocation.onActivityChange((event)=>{
      console.log("activity change", event);
      this.addEvent('onActivityChange', event)
    }));
    this.subscriptions.push(BackgroundGeolocation.onProviderChange((event) => {
      console.log("provider Change", event);
      if (event.status == 2) {
        // Permissions are not granted or location services are disabled
        console.log("we can show model, here");
      }
      let locationStatus:string;
      if(event.status == 3){
        console.log("Permission changed to: 'Always Allow'");
        locationStatus = 'Always Allow';
      } else if(event.status == 2){
        console.log("Permission changed to: 'While Using the App'");
        locationStatus = 'While Using the App';
      }else{
        console.log("Permission changed to: 'Denied'");
        locationStatus = 'Denied';
      }

        let data ={
          "load_id":this.getStoredLoadId(),
          "location_permission":locationStatus

        }
        this.authService.sendFCMToken(data)
        .subscribe(res=>{
          console.log("load with device token",res);
        })
      this.addEvent('onProviderChange', event);
    }))

    this.subscriptions.push(BackgroundGeolocation.onHttp((response) => {
      console.log('HTTP Response:', response.status, response.responseText);
    }));
    BackgroundGeolocation.ready({
      reset: true,
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      stopTimeout: 5,
      heartbeatInterval:900,
      preventSuspend:true,
      pausesLocationUpdatesAutomatically:false,
      stopOnTerminate: false,
      startOnBoot: true,
      debug: false,
      logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
      url: `http`,
      params:{
        load:this.getStoredLoadId()
      },
      batchSync: false,
      autoSync: true,
      foregroundService: true,
      notification: {
        channelName: "Location Tracking",
        title: 'Location Service',
        text: 'Running in the background',
        priority: BackgroundGeolocation.NOTIFICATION_PRIORITY_HIGH,
        sticky: false
      },
      schedule: [
        "1 17:30-21:00",
        "2-6 9:00-17:00",
        "2,4,6 20:00-00:00",
        "7 10:00-19:00"
      ],
      showsBackgroundLocationIndicator: true
    }).then(state => {
      this.ready = true;
      this.enabled = state.enabled;
      this.addEvent('State', state);
    });
  }

  addEvent(name:string, event:any){
    this.zone.run(()=>{
      this.events.push({
        name:name,
        json:JSON.stringify(event, null,2)
      });
      console.log("events background", this.events);
    })
  }

Relevant log output

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions