Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between two locations isn't right

I have used the algorithm on http://www.movable-type.co.uk/scripts/latlong.html to find the distance between two points.

My two points are

long1 = 51.507467;
lat1 = -0.08776;

long2 = 51.508736;
lat2 = -0.08612;

According to Movable Type Script the answer is 0.1812km

My application gives the result (d) as 0.230km

Check Haversine formula: http://www.movable-type.co.uk/scripts/latlong.html

    double R = 6371; // earth’s radius (mean radius = 6,371km)
    double dLat =  Math.toRadians(lat2-lat1);

    double dLon =  Math.toRadians(long2-long1); 
    a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2); 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    double d = R * c;
like image 277
Ally Avatar asked Jul 15 '10 16:07

Ally


2 Answers

Why to reinvent your own distance calculator, there is one built into the Location class.

Check out

distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results) 
Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them.
like image 192
Pentium10 Avatar answered Oct 24 '22 00:10

Pentium10


Your implementation is correct. The distance given those longitudes and latitudes should produce a distance of 0.230 km. The normal input for coordinates, however, is (latitude, longitude). Putting them in backwards (longitude, latitude) produces the incorrect distance of 0.1812 km.

like image 3
Robert Hui Avatar answered Oct 23 '22 23:10

Robert Hui