I developed an application that one of the features it has is to calculate the distance traveled by the user, for that I use a Service
and the LocationListener
API to request user location updates.
In the onLocationChanged
method, I calculate the distance traveled and saved in the local bank. What is happening is that sometimes this count of the distance covered is well above the estimate.
@Override
public void onLocationChanged(Location location) {
if (location != null) {
if (startCounter) {
if (!isFirstLocationFinded) {
latlon = new double[]{location.getLatitude(), location.getLongitude()};
isFirstLocationFinded = true;
} else {
double distance = calculateDistance(location);
//save in database
TrackingRace track = database.find(TrackingRace.class, ID);
if (track == null) {
TrackingRace trackingRace = new TrackingRace(ID, distance);
database.save(trackingRace);
} else {
double oldDistance = track.distance;
double totalDistance = distance + oldDistance;
TrackingRace trackingRace = new TrackingRace(ID, totalDistance);
database.update(trackingRace);
}
}
}
}
}
}
private double calculateDistance(Location location) {
double[] latlonNew = new double[]{location.getLatitude(),location.getLongitude()};
double distance = 0;
Location locationA = new Location("point A");
locationA.setLatitude(latlon[0]);
locationA.setLongitude(latlon[1]);
Location locationB = new Location("point B");
locationB.setLatitude(latlonNew[0]);
locationB.setLongitude(latlonNew[1]);
distance = locationA.distanceTo(locationB);
latlon = latlonNew.clone();
return distance;
}