Reputation: 1
I am writing an application for tracking my route. I am requesting updates from GPS every minute and it works fine. It shows me my exact point. When I want to calculate distance between current point and previous one it works ok, but form time to time it calculates distance totaly wrong (I moved about 200m and it retuned me a value over 10km). Does anyone know why this could happen?
Here is the function which I use:
iRoute += myGPSLocation.distanceTo(prevLocation);
Thanks in advance!
Upvotes: 0
Views: 3999
Reputation: 41
Stop using google's Location.distancebetween & location.distanceto functions. They don't work consistently.
Instead use the direct formula to calculate the distance:
double distance_between(Location l1, Location l2)
{
//float results[] = new float[1];
/* Doesn't work. returns inconsistent results
Location.distanceBetween(
l1.getLatitude(),
l1.getLongitude(),
l2.getLatitude(),
l2.getLongitude(),
results);
*/
double lat1=l1.getLatitude();
double lon1=l1.getLongitude();
double lat2=l2.getLatitude();
double lon2=l2.getLongitude();
double R = 6371; // km
double dLat = (lat2-lat1)*Math.PI/180;
double dLon = (lon2-lon1)*Math.PI/180;
lat1 = lat1*Math.PI/180;
lat2 = lat2*Math.PI/180;
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c * 1000;
log_write("dist betn "+
d + " " +
l1.getLatitude()+ " " +
l1.getLongitude() + " " +
l2.getLatitude() + " " +
l2.getLongitude()
);
return d;
}
Upvotes: 1
Reputation: 28767
distanceTo() works correctly.
The error is on your side, most probable algorithmic one, e.g if there is no GPS fix available, and the phone takes a GSM cell based location, this of course can be off by 1000m.
For your app that probably wants to sum up the distance travelled, take only GPS fixes, don't use another LocationProvider than GPS!
Upvotes: 1