Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate distance between 2 GPS coordinates

How do I calculate distance between two GPS coordinates (using latitude and longitude)?

like image 555
nicudotro Avatar asked Dec 13 '08 22:12

nicudotro


People also ask

How do I calculate distance between GPS coordinates in Excel?

Here are the formulas for degree coordinates: Cell B5: =distvincenty(B2,C2,B3,C3) Cell D5: =MOD(DEGREES(ATAN2(COS(B2*PI()/180) *SIN(B3*PI()/180)-SIN(B2*PI()/180) *COS(B3*PI()/180) *COS(C3*PI()/180-C2*PI()/180), SIN(C3*PI()/180-C2*PI()/180) *COS(B2*PI()/180)))+360,360)

How far apart are coordinates?

Each degree of latitude is approximately 69 miles (111 kilometers) apart.


2 Answers

Calculate the distance between two coordinates by latitude and longitude, including a Javascript implementation.

West and South locations are negative. Remember minutes and seconds are out of 60 so S31 30' is -31.50 degrees.

Don't forget to convert degrees to radians. Many languages have this function. Or its a simple calculation: radians = degrees * PI / 180.

function degreesToRadians(degrees) {   return degrees * Math.PI / 180; }  function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {   var earthRadiusKm = 6371;    var dLat = degreesToRadians(lat2-lat1);   var dLon = degreesToRadians(lon2-lon1);    lat1 = degreesToRadians(lat1);   lat2 = degreesToRadians(lat2);    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +           Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));    return earthRadiusKm * c; } 

Here are some examples of usage:

distanceInKmBetweenEarthCoordinates(0,0,0,0)  // Distance between same                                                // points should be 0 0  distanceInKmBetweenEarthCoordinates(51.5, 0, 38.8, -77.1) // From London                                                           // to Arlington 5918.185064088764 
like image 77
cletus Avatar answered Sep 20 '22 10:09

cletus


Look for haversine with Google; here is my solution:

#include <math.h> #include "haversine.h"  #define d2r (M_PI / 180.0)  //calculate haversine distance for linear distance double haversine_km(double lat1, double long1, double lat2, double long2) {     double dlong = (long2 - long1) * d2r;     double dlat = (lat2 - lat1) * d2r;     double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);     double c = 2 * atan2(sqrt(a), sqrt(1-a));     double d = 6367 * c;      return d; }  double haversine_mi(double lat1, double long1, double lat2, double long2) {     double dlong = (long2 - long1) * d2r;     double dlat = (lat2 - lat1) * d2r;     double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);     double c = 2 * atan2(sqrt(a), sqrt(1-a));     double d = 3956 * c;       return d; } 
like image 42
Peter Greis Avatar answered Sep 21 '22 10:09

Peter Greis