Calculate distance between two GPS coordinates

2 votes · 1 comment

These functions compute the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid. Best done with Android's Location class.

raw ·
copy
· download
// If you have just the coordinates: Location.distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results) // If you have two Location objects: float distance_meters = Location1.distanceTo(Location2) // This is an approximation function, which does not take the private double gps2m(float lat_a, float lng_a, float lat_b, float lng_b) { float pk = (float) (180/3.14169); float a1 = lat_a / pk; float a2 = lng_a / pk; float b1 = lat_b / pk; float b2 = lng_b / pk; float t1 = FloatMath.cos(a1) * FloatMath.cos(a2) * FloatMath.cos(b1) * FloatMath.cos(b2); float t2 = FloatMath.cos(a1) * FloatMath.sin(a2) * FloatMath.cos(b1) * FloatMath.sin(b2); float t3 = FloatMath.sin(a1) * FloatMath.sin(b1); double tt = Math.acos(t1 + t2 + t3); return 6366000*tt; }
Add a comment

1 Comment

The value of PI should be 3.14159 or Math.PI. And I guess the third comment is missing "oblateness of the earth into account".

Reply · March 26, 2011, 2:11 a.m.