If I have two GPS locations, say 51.507222, -0.1275 and 48.856667, 2.350833, what formula could I use to calculate the distance between the two? I've heard a lot about a haversine formula, but can't find any information about it, or how to apply it to C.
I've written the following code, however, it's very innacurate. Anybody know why? I can't figure it out. The problem comes from the function itself, but I don't know what it is.
float calcDistance(float A, float B, float C, float D)
{
float dLat;
float dLon;
dLat = (C - A);
dLon = (D - B);
dLat /= 57.29577951;
dLon /= 57.29577951;
float v_a;
float v_c;
float distance;
v_a = sin(dLat/2) * sin(dLat/2) + cos(A) * cos(C) * sin(dLon/2) * sin(dLon/2);
v_c = 2 * atan2(sqrt(v_a),sqrt(1-v_a));
distance = r * v_c;
return distance;
}
Your code is absolutely correct.
I would rename parameters
A
,B
,C
andD
tolat1
,lon1
,lat2
andlon2
.It returns the distance in kilometers. You need to define
r
as 6371, roughly the radius of the earth.What you're looking for is the great circle distance.
Maybee its too late, but this is the reason of the inaccurate calculation: -> A and C (lat1 and lat2) must also be converted from degree to radians
regards, omeier
This page has a block of Javascript which I'm sure you could adapt easily enough in C: