transistorsoft / cordova-background-geolocation-lt

The most sophisticated background location-tracking & geofencing module with battery-conscious motion-detection intelligence for iOS and Android.
http://www.transistorsoft.com/shop/products/cordova-background-geolocation
Other
655 stars 277 forks source link

For identical travel path total calculated distance is different from the location updates in server . #1427

Closed RintuMondal06 closed 1 week ago

RintuMondal06 commented 6 months ago

Your Environment

We are using this plugin in a cab booking application. Now we are having an issue in calculating the total distance of a ride, the calculated distance is different for identical rides on the same route . We are storing all the locations in server when a ride starts and stoping the http sync process when the ride ends. We want the locations to be saved in server only when a ride is going on. The total distance is being calculated by summing up the difference between all consecutive location of a ride.

// BackgroundGeolocation Plugin configuration
    BackgroundGeolocation.ready(
      {
        reset: true,
        logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
        desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
        stopOnTerminate: false,
        allowIdenticalLocations: false,
        persistMode: BackgroundGeolocation.PERSIST_MODE_LOCATION,
      },
      (state) => {
        console.log('[ready] BackgroundGeolocation is ready to use');
        if (!state.enabled) {
          BackgroundGeolocation.start();
        }
      }
    );

// Manually starting the sync process when the ride starts
  async startIntervalDistance() {
        await BackgroundGeolocation.destroyLocations();
        BackgroundGeolocation.setConfig({
          url: 'BACKEND_URL',
          params: { // ride id },
          locationUpdateInterval: 8000,
          distanceFilter: 0,
          autoSync: true,
          allowIdenticalLocations: false
        });
    }

// Manually stoping the sync process when the ride ends
  stopDistanceAPI() {
          BackgroundGeolocation.setConfig({
              autoSync: false,
          });
      }
christocracy commented 6 months ago

If your driver is stopped, you should tell the plugin to .stop().

Setting the url to '' is not going to stop the plugin continuing to record locations and insert them into its database.

See api docs Config.maxRecordsToPersist.

christocracy commented 6 months ago

Also read the api docs "HTTP Guide", linked througout.

RintuMondal06 commented 6 months ago

If your driver is stopped, you should tell the plugin to .stop().

Setting the url to '' is not going to stop the plugin continuing to record locations and insert them into its database.

See api docs Config.maxRecordsToPersist.

@christocracy Thank you very much for your reply!! are you suggesting making the plugin start/stop with respect to ride start and end? If yes how can I prevent the plugin from recording the locations? Because with .ready() the plugin starts recording the locations.

christocracy commented 6 months ago

Calling .ready(config) restores the plugin to its last known state according to State.enabled.

The plugin stores State.enabled in permanent storage. It is "remembered" even after app terminate / device reboot.

christocracy commented 6 months ago

If you call .stop(), terminate then restart your app, you will find that State.enabled == false and the plugin will NOT call .start() upon itself after .ready(config) is called.

BackgroundGeolocation.ready(config).then((state) => {
  console.log('State.enabled? ', state.enabled);
});
RintuMondal06 commented 6 months ago

For the first time when the app is loaded with .ready() called then state.enabled is by default true right? But in my case i want to track location only when a ride is on-going. So should I call .stop() at the first time by myself?

christocracy commented 6 months ago

Called then state.enabled is by default true right?

No. The plugin is disabled by default. Calling .ready(config) does NOT imply "start tracking". Only calling .start() initiates tracking.

RintuMondal06 commented 6 months ago

Thanks for your help @christocracy !! I am stuck here for a long time. I'll change my code and check.

gfernandez87 commented 1 month ago

Dear good afternoon, I wanted to ask you if it is mandatory to configure an api (url). I have to make an application that retrieves the coordinates and inserts them into a SQLite database, but the application will not have an internet connection so I cannot configure an API, is it possible for it to work locally? Thank you so much

christocracy commented 1 month ago

No, it's not mandatory. Simply DO NOT even provide an url.

Be aware that the plug-in inserts each recorded location into its own SQLite db and collects 3 days worth by default. You will may want to configure Config.persistMode accordingly (PERSIST_MODE_NONE).

If you wish to take advantage of the plug-in's SQLite db, see .getLocations and .destroyLocations.

gfernandez87 commented 1 month ago

Dear, thank you very much for your response. I'll bother you with two more queries if possible. I am setting locationUpdateInterval to 1 second, because I need to show the time in which the vehicle is stopped, the problem I have is that initially the tracking is not executed every one second, until it detects a movement, is this normal? . And the other problem I have is that for example when I am in the "walking" state and I brake there is a delay in changing to the "still" state of approximately 15 seconds, the same when I change from "still" to "walking". I am setting it up as follows:

configureBackgroundGeolocationDos() {
    // 1.  Listen to events.
    BackgroundGeolocation.onLocation(location => {
      // Calcular la distancia entre la ubicación actual y la anterior
      console.log('[location] - ', location);
      this.listaPuntosViaje.push(location.coords)
      if (!this.ubicacionAnterior || this.ubicacionAnterior == null) {
        this.ubicacionAnterior = location.coords;
        return;
      }

      this.mostrarMensaje("ACTIVIDAD " + location.activity.type)
      if (location.activity.type == 'running') { //CORRIENDO

      }
      if (location.activity.type == 'still') { //CORRIENDO
        this.tiempoDeParadaSegundos += 1;
      }
      if (location.activity.type == 'on_foot') { // A PIE

      }

      if (location.activity.type == 'on_bicycle') { // EN BICICLETA

      }
      if (location.activity.type == 'in_vehicle') { // EN VEHICULO

      }

      if (location.activity.type == 'unknown') { // DESCONOCIDO

      }

      let velocidad = location.coords.speed == undefined ? 0 : location.coords.speed;
      if (velocidad > 0) {
       this.velocidad = velocidad * 3.6; // Convertir de m/s a km/h
      }
      else {
        this.velocidad = 0;
      }

      if (location.activity.type == 'walking' || location.activity.type == 'in_vehicle') {

        this.mostrarMensaje(location.activity.type)

        const distancia = this.pruebaDistancia(this.ubicacionAnterior.latitude, this.ubicacionAnterior.longitude,
          location.coords.latitude, location.coords.longitude)
        this.distanciaRecorrida += distancia;

      }
      this.cdr.detectChanges();

      this.ubicacionAnterior = location.coords;

    });

    BackgroundGeolocation.onMotionChange(event => {
      console.log('[motionchange] - ', event.isMoving, event.location);
    });

    BackgroundGeolocation.onHttp(response => {
      console.log('[http] - ', response.success, response.status, response.responseText);
    });

    BackgroundGeolocation.onProviderChange(event => {
      console.log('[providerchange] - ', event.enabled, event.status, event.gps);
    });

    // 2.  Configure the plugin with #ready
    BackgroundGeolocation.ready({

      reset: true,
      debug: true,
      logLevel: BackgroundGeolocation.LOG_LEVEL_OFF,
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 0,
      disableElasticity: true,
      locationAuthorizationRequest: "Any",
      locationUpdateInterval: 2000,
      fastestLocationUpdateInterval: 2000,
      maxDaysToPersist: 0, maxRecordsToPersist: 0, //VER ESTO DESHABILITA GUARDAR EN SQLLITE 
      stopOnStationary: false,
      // url: 'http://my.server.com/locations',
      allowIdenticalLocations: false,
      autoSync: true,
      stopOnTerminate: true,
      startOnBoot: false, persistMode: BackgroundGeolocation.PERSIST_MODE_NONE,
      notification: {
        title: 'TEST', 
        text: 'TEXT', 
        color: '#FFFFFF', 
        channelName: 'Geolocation', 
        priority: -1
    },
    }, (state) => {
      console.log('[ready] BackgroundGeolocation is ready to use');
      if (!state.enabled) {
        // 3.  Start tracking.
        BackgroundGeolocation.start();
      }
    });
  }

I hope you can help me and thank you very much in advance!!

christocracy commented 1 month ago

Please learn to syntax highlight fenced codeblocks

christocracy commented 1 month ago

the problem I have is that initially the tracking is not executed every one second, until it detects a movement, is this normal?

The native location api returns locations when it feels like it. The plug-in merely "turns it on".

when I am in the "walking" state and I brake there is a delay in changing to the "still" state of approximately 15 seconds

The same go for the native location api. The plug-in turns it ON -- it's totally up to the OS to return results when it feels like it. There's nothing you can do to "fine tune" it or make it returns results faster.

gfernandez87 commented 1 month ago

Thank you again for your prompt response! One last question, I understand that it is not, but just in case I ask it, there is no functionality that returns the kilometers or meters traveled since BackgroundGeolocation.start() was started; until BackgroundGeolocation.stop()? is finished. This should be calculated by taking the distance between the last coordinate and the new coordinate and accumulating it in a variable, right?

Sorry for the inconvenience and thank you again!

christocracy commented 1 month ago

Search the api docs "odometer"

gfernandez87 commented 1 month ago

Search the api docs "odometer"

Thank you so much!!

github-actions[bot] commented 3 weeks ago

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] commented 1 week ago

This issue was closed because it has been inactive for 14 days since being marked as stale.