Distance between two GPS coordinates (in meter)

2 votes · 7 comments

A simple function that takes two GPS coordinates as input and outputs the distance between them in meter. More approaches can be found here

raw ·
copy
· download
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

7 Comments

This only works if the points are close enough that you can omit that earth is not regular shape. Google has an API that works correctly even on a longer distance, but you have to make a HTTP request to get this.

Reply · May 27, 2009, 3:24 p.m.

It's not perfect, but you can use this function (C#) to approximate the average ellipsoid radius between points:

ellipsoidRadius = 6378.137 * (1 - 0.0033493 * Math.Pow(Math.Sin(0.5 * (Lat1 + Lat2)), 2));

Beats making an HTTP request for each calculation, especially for mobile apps.

Reply · June 9, 2009, 7:36 p.m.

You can simply use the API function for this:

http://developer.android.com/reference/android/location/Location.html#distanceTo(android.location.Location)

Reply · June 21, 2009, 3:39 a.m.

Just thought I'd point out that PI is actually 3.14159 not 3.14169.

Reply · June 29, 2009, 1:54 p.m.

Location.distanceBetween gives meters + bearing.

Reply · June 29, 2009, 2:37 p.m.

Quite inspiring,

Anyway, thanks for the post

Reply · Aug. 18, 2009, 4:19 p.m.

API DistanceTo and Bearing To are quite imperfect unless your 2 locations points are 100 meter apart at least

Reply · Sept. 15, 2009, 10:48 p.m.