Sfoglia il codice sorgente

location update fix

Viktoriia 4 mesi fa
parent
commit
a938127c63
1 ha cambiato i file con 31 aggiunte e 21 eliminazioni
  1. 31 21
      src/utils/backgroundLocation.ts

+ 31 - 21
src/utils/backgroundLocation.ts

@@ -17,14 +17,11 @@ TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
     const { locations } = data as any;
     let lastLocationSentTime =
       (storage.get('last_location_sent_time', StoreType.NUMBER) as number) ?? 0;
+    let lastLatitude = storage.get('last_latitude', StoreType.NUMBER) as number | null;
+    let lastLongitude = storage.get('last_longitude', StoreType.NUMBER) as number | null;
 
     if (locations && locations.length > 0) {
       const now = Date.now();
-      if (now - lastLocationSentTime < 60 * 1000) {
-        return;
-      }
-      storage.set('last_location_sent_time', now);
-
       const { coords } = locations[0];
       const token = storage.get('token', StoreType.STRING);
 
@@ -32,23 +29,36 @@ TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
         return;
       }
 
-      try {
-        const response = await axios.postForm(
-          API_URL + '/' + API.UPDATE_LOCATION,
-          {
-            token,
-            lat: coords.latitude,
-            lng: coords.longitude
-          },
-          {
-            headers: {
-              Platform: Platform.OS,
-              'App-Version': APP_VERSION
+      const getThreeDigits = (num: number) => Math.floor(num * 1000);
+
+      const latitudeChanged =
+        !lastLatitude || getThreeDigits(lastLatitude) !== getThreeDigits(coords.latitude);
+      const longitudeChanged =
+        !lastLongitude || getThreeDigits(lastLongitude) !== getThreeDigits(coords.longitude);
+
+      if (latitudeChanged || longitudeChanged || now - lastLocationSentTime >= 60 * 1000) {
+        storage.set('last_location_sent_time', now);
+        storage.set('last_latitude', coords.latitude);
+        storage.set('last_longitude', coords.longitude);
+
+        try {
+          const response = await axios.postForm(
+            API_URL + '/' + API.UPDATE_LOCATION,
+            {
+              token,
+              lat: coords.latitude,
+              lng: coords.longitude
+            },
+            {
+              headers: {
+                Platform: Platform.OS,
+                'App-Version': APP_VERSION
+              }
             }
-          }
-        );
-      } catch (sendError) {
-        console.error('[BackgroundLocation] Sending location failed:', sendError);
+          );
+        } catch (sendError) {
+          console.error('[BackgroundLocation] Sending location failed:', sendError);
+        }
       }
     }
   }