I need to calculate distance between two GPS points. I found this function in earlier post:
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
I tried it, and it does not make sense. Let's say I did not move, thus lat1
and lat2
are the same. So, dLat
and dLon
would both be 0. Thus, term a
would be 0. Term c = 2 * Math.atan2(0,1) = 3.141593
(I used Excel to get this number), and the distance d = 20015.08 km
.
I am calculating distance of a vehicle moving every second given two GPS points. I am expecting small number. What is wrong here?
I used this code - it worked fine.
public static double distance(MyLocation p1, MyLocation p2) {
double theta = p1.mLongitude - p2.mLongitude;
String unit = "K";
double dist = Math.sin(deg2rad(p1.mLatitude)) * Math.sin(deg2rad(p2.mLatitude))
+ Math.cos(deg2rad(p1.mLatitude)) * Math.cos(deg2rad(p2.mLatitude)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
it calculates distances in kilometers.