I am trying to implement a functionality, that if a user travels, then his/her live location will be captured in every interval of 10 sec. I am saving the captured lat-longs in local database and then run a API after every 10 mins to save data on server.
In every 10 secs I am calculating the distance between last last lat-long captured and updated lat-long captured.
When I tested it, I travelled around 35 KM, but total distance calculate was around 400 KM. On again testing, I travelled around 15 KM, but total distance calculate was around 150 KM.
Please anyone suggest what am I doing wrong. Or is there any alternative solution to track my path on which I travelled and total distance I covered.
For this I am using the below code to run the timer in every 10 secs
Timer.periodic(const Duration(seconds: 10), (timer) async {
await CommonMethods.getCurrentLocationDateTime();
});
In every 10 secs, I run the below code:
static Future getCurrentLocationDateTime() async {
_result = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.bestForNavigation,
);
if (_updatedLatitude == null && _updatedLongitude == null) {
_previousLatitude = _result!.latitude;
_previousLongitude = _result!.longitude;
} else {
_previousLatitude = _updatedLatitude;
_previousLongitude = _updatedLongitude;
}
_updatedLatitude = _result!.latitude;
_updatedLongitude = _result!.longitude;
// Save data in a local variable
Map<String, String> _currentLatLong = {
"lat": _result!.latitude.toStringAsFixed(8),
"long": _result!.longitude.toStringAsFixed(8),
};
CommonEntities.travelHistoryLatLng.add(_currentLatLong);
// Update previous and current location names
await placemarkFromCoordinates(_updatedLatitude!, _updatedLongitude!)
.then((List<Placemark> placemarks) {
_previousLocationName = (_currentLocationName == "")
? placemarks[0].name!
: _currentLocationName;
_currentLocationName = placemarks[0].subLocality!;
}).catchError((e) {
debugPrint(e.toString());
});
// Check if device is not moved for more than 2 hours
// if not moved then stop the timer
if (CommonEntities.travelHistoryLatLng.toSet().length == 1) {
CommonEntities.idealStateTravelTimeSpent += 10;
if (CommonEntities.idealStateTravelTimeSpent >= 7200) {
CommonEntities.idealStateTravelTimeSpent = 0;
// BackgroundLocation.stopLocationService();
if (CommonEntities.travelTimer != null) {
CommonEntities.travelTimer!.cancel();
}
CommonEntities.isTravelTimerActive = false;
CommonEntities.workEndTime =
CommonEntities.travelTrackingDetails["current_date_time"];
}
} else {
CommonEntities.idealStateTravelTimeSpent = 0;
}
// Get Current date time of captured lat-longs
_currentDateTime = DateTime.now();
_currentDateTimeString = _currentDateTime.year.toString() +
"-" +
_currentDateTime.month.toString() +
"-" +
_currentDateTime.day.toString() +
" " +
_currentDateTime.hour.toString() +
":" +
_currentDateTime.minute.toString();
if (CommonEntities.workStartTime == "00:00") {
CommonEntities.workStartTime = _currentDateTime.hour.toString() +
":" +
_currentDateTime.minute.toString();
// LocalSharedPreferences().setWorkStartTime();
}
// Update the total distance covered in 10 min
updateDistanceTraveled();
print("Total Distance Covered: " + CommonEntities.travelTrackingDetails["total_distance_covered"]);
// Call API to save travel data in every 10 minutes.
if (CommonEntities.totalTravelsecondsCount == 600) {
// Calculate the time before 10 min and for time interval in post params
String _currentTime = _currentDateTime.hour.toString() +
':' +
_currentDateTime.minute.toString();
DateTime _dateTimeBeforeTenMin =
_currentDateTime.subtract(const Duration(minutes: 10));
String _timeBeforeTenMin = _dateTimeBeforeTenMin.hour.toString() +
':' +
_dateTimeBeforeTenMin.minute.toString();
String _tempDistanceTravelled =
CommonEntities.travelTrackingDetails["total_distance_covered"];
CommonEntities.travelTrackingDetails["total_distance_covered"] = "";
_distanceTravelled = 0.0;
// Create post params value
Map<String, dynamic> params = {
'lat_long': jsonEncode(CommonEntities.travelHistoryLatLng),
'date': _currentDateTime.day.toString() +
'-' +
_currentDateTime.month.toString() +
'-' +
_currentDateTime.year.toString() +
' ' +
_currentDateTime.hour.toString() +
':' +
_currentDateTime.minute.toString() +
':' +
_currentDateTime.second.toString(),
'distance_covered': _tempDistanceTravelled,
'userID': await LocalSharedPreferences().getUserId(),
'time_interval': _timeBeforeTenMin + '-' + _currentTime,
'location_name': _currentLocationName,
'status': 'progress',
};
// Call the API to save travel history of 10 min of server
HomeProvider().saveTravelDetails(params);
// await LocalSharedPreferences().saveTravelHistoryLatLng();
// Reset the timer of 10 min, clear lat-long history of 10 min
CommonEntities.totalTravelsecondsCount = 0;
CommonEntities.travelHistoryLatLng = [];
}
CommonEntities.totalTravelsecondsCount += 10;
// Save latlong and date time
// BOC: commented logging of lat-long as the same is not required in final app
// by shubham.bansal2
AppLogs().logToFile(
_result!.latitude.toString() + "-" + _result!.longitude.toString(),
_currentDateTimeString);
CommonEntities.travelTrackingDetails["updated_latitude"] =
_updatedLatitude!.toStringAsFixed(8);
CommonEntities.travelTrackingDetails["updated_longitude"] =
_updatedLongitude!.toStringAsFixed(8);
CommonEntities.travelTrackingDetails["updated_location_name"] =
_currentLocationName;
CommonEntities.travelTrackingDetails["previous_latitude"] =
_previousLatitude!.toStringAsFixed(8);
CommonEntities.travelTrackingDetails["previous_longitude"] =
_previousLongitude!.toStringAsFixed(8);
CommonEntities.travelTrackingDetails["previous_location_name"] =
_previousLocationName;
CommonEntities.travelTrackingDetails["total_distance_covered"] =
_distanceTravelled.toStringAsFixed(8);
CommonEntities.travelTrackingDetails["current_date_time"] =
_currentDateTimeString;
}
Also for Distance, I am using the below code:
static updateDistanceTraveled() {
var p = 0.017453292519943295;
var c = cos;
var a = 0.5 -
c((_updatedLatitude! - _previousLatitude!) * p) / 2 +
c(_previousLatitude! * p) *
c(_updatedLatitude! * p) *
(1 - c((_updatedLongitude! - _previousLongitude!) * p)) /
2;
_distanceTravelled = double.parse(CommonEntities.travelTrackingDetails["total_distance_covered"]);
_distanceTravelled += (12742 * asin(sqrt(a))).toDouble();
CommonEntities.travelTrackingDetails["total_distance_covered"] =
_distanceTravelled.toStringAsFixed(5);
}