react-native-google-fit icon indicating copy to clipboard operation
react-native-google-fit copied to clipboard

getWorkoutSession(opt) returning incorrect distance field values

Open JDMathew opened this issue 2 years ago • 1 comments

I am calling getWorkoutSeession options but getting workout results but the distance measurements are not comparable to the distance shown in Google Fit app. I think this may be due to TYPE_DISTANCE_DELTA data type, each data point represents the distance covered, in meters, since the last reading but I don't know how to fix this

JDMathew avatar May 15 '22 23:05 JDMathew

I have been able to confirm that this issue is only happening on some devices. However it's more than 50% of my users. As a work around I recalculated the distance per workout with the getDailyDistanceSamples function.

Example code here:

 const workouts = (await GoogleFit.getWorkoutSession(workoutOpt))
  // if workouts is empty or undefined, we don't have any data to sync
  if (workouts === undefined || isEmptyArray(workouts)) return
  // reorder workouts array by endDate to match the order for syncing from previous end date to work correctly and not have missed activities
  const workoutsByEndDate = workouts.sort((a, b) => {
    if (a.endDate < b.endDate) return -1
    if (a.endDate > b.endDate) return 1
    return 0
  })
  // loop through workouts, format data and  sync with backend
  for (let index = 0; index < workoutsByEndDate.length; index++) {
    const workout = workoutsByEndDate[index]
    // NOTE: workout distance is incorrect on some devices so we need to get it from the Distance Samples for the time period of the session
    const recalculatedDistance = await GoogleFit.getDailyDistanceSamples({ startDate: moment(workout?.startDate).format(), endDate: moment(workout?.endDate).format() })
    const distance = recalculatedDistance?.reduce((acc, curr) => acc + curr?.distance, 0)
    const duration = moment.duration(moment(workout.endDate).diff(moment(workout.startDate))).asSeconds()
    const calories = Math.round(parseFloat(workout.calories) * 100) / 100 || 0
    const workoutActivity : ActivitySession = {
      type: getActivityName(workout.activity),
      calories: calories,
      startTime: moment(workout.startDate, true).format(),
      endTime: moment(workout.endDate, true).format(),
      distance: Math.round(distance), // round to the nearest meter
      duration: Math.round(duration),
    }
    await sendActivity(workoutActivity)
  }

JDMathew avatar May 18 '22 17:05 JDMathew