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
656 stars 277 forks source link

Plugin configuration issue #1413

Closed Kshitij-2427 closed 6 days ago

Kshitij-2427 commented 9 months ago

I have an Ionic Cordova mobile app project in which I have a background Geolocation Tracking feature. I have gone through the docs and done the configuration according to it only. Still, In the beginning, I am getting location updates and API calls properly according to the configuration but after sometime I used to get only location updates when the app is in the background. As soon as you switch the app to the foreground it calls the API at a time out of which some are successful and some are failing. Data that is stored on the server is like for the same time multiple locations are showing. Why it is happening like this?

My use case is every location update it should call the API and insert the data to the server.

JSON which I need to send to my server -

const data = JSON.stringify({ "user_id": this.globals.userInfo['user_id'].toString(), "latitude": location.coords.latitude, // from location update response "longitude": location.coords.longitude, // from location update response "created_time": moment().format("YYYY-MM-DD HH:mm:ss"), "created_date": moment().format("YYYY-MM-DD") });

Service created by me- configureBackgroundGeolocation() { const isLoggedIn = this.isUserLoggedIn(); const isStarted = this.getIsBackgroundGeolocationStarted(); console.log("Configuring BGL") console.log(isLoggedIn)

if(!isStarted){

  const config = {
    debug: false,
    reset: true,
    logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
    desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
    distanceFilter: 0,
    stopOnTerminate: false,
    startOnBoot: true,
    locationUpdateInterval: 60000, // 1 minutes in milliseconds
    autoSync: true,
    url: 'https://00.stpl.aa00.00.skanray.net:8020/iCRM_mobile/index.php/insert_live_location_api',
    // params: {
    //   foo: 'bar'
    // }
    // httpRootProperty:".",
    // locationTemplate:
    //   '{"lat":<%= latitude %>,"lng":<%= longitude %>}',
    // extras: {
    //   user_id: "648",
    //   created_time: moment().format("YYYY-MM-DD HH:mm:ss"),
    //   created_date: moment().format("YYYY-MM-DD")
    // },
  };

  this.platform.ready().then(() => {
    try {
      BackgroundGeolocation.ready(config, (state) => {
        console.log('[ready] BackgroundGeolocation is ready to use');
        console.log(state.enabled);
        if (!state.enabled) {
          BackgroundGeolocation.start();
          console.log("Background Tracking Started");
          this.setIsBackgroundGeolocationStarted(true);
        } else {
          console.log("State is enabled");
        }
      });
    } catch (error) {
      console.error("Error in checking background ready:", error);
    }
  });

  BackgroundGeolocation.onLocation((location) => {
    console.log('[location] -', location);
    console.log("[Latitude]: " + location.coords.latitude);

    const data = JSON.stringify({
      "user_id": this.globals.userInfo['user_id'].toString(),
      "latitude": location.coords.latitude,
      "longitude": location.coords.longitude,
      "created_time": moment().format("YYYY-MM-DD HH:mm:ss"),
      "created_date": moment().format("YYYY-MM-DD")
    });

    var body1 = window.btoa(data);
    console.log("Body sending to server: "+data)

    setTimeout(() => {
      console.log("AAAAAAAAAAAAAAAAAAAAAAa")
      this.zone.run(() => {
        console.log("In Zone Run")
        this.http.post(SERVER_URL + LIVE_LOC_INSERT, body1).subscribe(
          result => {
            console.log("result" + JSON.stringify(result));
          },
          err => {
            console.log("err" + JSON.stringify(err));
          }
        );
        console.log("BBBBBBBBBBBBBBBBBBBBBBbbbb")

        //Insert Location using Web Socket
        // this.track =
        // this.globals.userInfo['user_id'].toString() +
        // "," +
        // location.coords.latitude +
        // "," +
        // location.coords.longitude;

        // this.socket.emit(
        //   "createMessage",
        //   {
        //     text: this.track
        //   },
        //   function (res) {
        //     console.log(res);
        //   }
        // );

      });
    }, 1000);

    console.log("CCCCCCCCCCCCCCCCCcccc")

  },
  (error) => {
    console.error("Location error:", error);
  });

}

}

christocracy commented 9 months ago

If you want to take control over uploading data to your server with you own JavaScript code instead of using the plug-in’s built-in HTTP service, that’s up to you.

however, you will have a major problem uploading location data in the Android terminated state, where your JavaScript code no longer exists. You would have to implement your uploading code in pure Java. See api docs Config.enableHeadless.

If you choose to take advantage of the plug-in’s built-in http service and Config.locationTemplate, there are certain things which are not possible and you will likely need to modify your server to consume what the data format the plugin allows.

Kshitij-2427 commented 9 months ago

How should I configure my server. What is the format of the plugin? Main issue is why each location update Is called two times once interval is reached?

On Thu, Aug 10, 2023, 18:47 Chris Scott @.***> wrote:

If you want to take control over uploading data to your server instead of using the plug-in’s built-in HTTP service, that’s up to you.

however, you will have a major problem uploading location data in the Android terminated state, where your JavaScript code no longer exists. You would have to implement your uploading code in pure Java. See api docs Config.enableHeadless.

If you choose to take advantage of the plug-in’s built-in http service and Config.locationTemplate, there are certain things which are not possible and you will likely need to modify your server to consume what the data format the plugin allows.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1413#issuecomment-1673202992, or unsubscribe https://github.com/notifications/unsubscribe-auth/BAF5PNJKUYLM3GJ3DO7X7KLXUTNPZANCNFSM6AAAAAA3LOPYWY . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1413/1673202992@ github.com>

christocracy commented 9 months ago

How should I configure my server. What is the format of the plugin?

If you use locationTemplate, the format is however you define it. See API docs Config.locationTemplate. If you don't use the locationTemplate, the default Location Data Schema is used. The plugin POSTs JSON.

why each location update Is called two times once interval is reached?

I don't know what you mean by that.

christocracy commented 9 months ago

I suggest you observe the incoming JSON from the plugin by printing the JSON received into your server logs.

Kshitij-2427 commented 9 months ago

Don't have access to server. Are you asking me to print each location update response? As soon as location updates what response we are getting is it!?

On Thu, Aug 10, 2023, 20:29 Chris Scott @.***> wrote:

I suggest you observe the incoming JSON from the plugin by printing the JSON received into your server logs.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/cordova-background-geolocation-lt/issues/1413#issuecomment-1673392793, or unsubscribe https://github.com/notifications/unsubscribe-auth/BAF5PNKQHQNUTNGRPSQCQ6DXUTZODANCNFSM6AAAAAA3LOPYWY . You are receiving this because you authored the thread.Message ID: <transistorsoft/cordova-background-geolocation-lt/issues/1413/1673392793@ github.com>

christocracy commented 9 months ago

If you don’t have access to the server, it’s going to be very difficult for you.

soon as location updates what response we are getting is it!?

Response from what?

Kshitij-2427 commented 9 months ago

Service created to configure and capture location in the background

I can ask the server guy to make changes, but at least I should know what structure this plugin is using.

configureBackgroundGeolocation() {

const isStarted = this.getIsBackgroundGeolocationStarted();

if(!isStarted){

  const config = {
    debug: false,
    reset: true,
    logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
    desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
    distanceFilter: 0,
    stopOnTerminate: false,
    startOnBoot: true,
    locationUpdateInterval: 600000, // 10 minutes in milliseconds
    autoSync: true,
    url: 'https://00.stpl.aa00.00.sabado.net:8020/iC_mobile/index.php/insert_live_location_api',
  };

  this.platform.ready().then(() => {
    try {
      BackgroundGeolocation.ready(config, (state) => {

        if (!state.enabled) {
          BackgroundGeolocation.start();

          this.setIsBackgroundGeolocationStarted(true);
        }
      });
    } catch (error) {
      console.error("Error in checking background ready:", error);
    }
  });

  BackgroundGeolocation.onLocation((location) => {
    console.log('[location] -', location);
    console.log("[Latitude]: " + location.coords.latitude);
    console.log("[Longitude]: " + location.coords.longitude);

    const data = JSON.stringify({
      "user_id": this.globals.userInfo['user_id'].toString(),
      "latitude": location.coords.latitude,
      "longitude": location.coords.longitude,
      "created_time": moment().format("YYYY-MM-DD HH:mm:ss"),
      "created_date": moment().format("YYYY-MM-DD")
    });

    var body1 = window.btoa(data);
    console.log("Body sending to server: "+data)

    setTimeout(() => {

      this.zone.run(() => {
        this.http.post(SERVER_URL + LIVE_LOC_INSERT, body1).subscribe(
          result => {
            console.log("result" + JSON.stringify(result));
          },
          err => {
            console.log("err" + JSON.stringify(err));
          }
        );

      });
    }, 1000);

  },
  (error) => {
    console.error("Location error:", error);
  });

}

}

christocracy commented 9 months ago

https://github.com/transistorsoft/cordova-background-geolocation-lt/wiki/Location-Data-Schema#http-post-schema

github-actions[bot] commented 2 weeks ago

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

github-actions[bot] commented 6 days ago

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