5

How to calculate the distance between 2 places by using the GPS coordinates?

uɐɪ
  • 2,482
  • 1
  • 21
  • 23
  • 1
    Duplicate of http://stackoverflow.com/questions/1420045/how-to-find-distance-from-the-latitude-and-longitude-of-two-locations – Lior Kogan May 27 '11 at 07:49
  • You may be using this algorithm in an embedded environment but there is nothing in the question to link it to embedded computing. Question re-tagged. – uɐɪ May 31 '11 at 15:01

2 Answers2

9

You have to use the haversine formula: Haversine formula:

R = earth’s radius (mean radius = 6,371km)

Δlat = lat2− lat1

Δlong = long2− long1

a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)

c = 2.atan2(√a, √(1−a))

d = R.c

Where d is distance (your solution) and all the angles must be in radians

Look for the haversine library, and in C:

#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;
}
dLobatog
  • 3,474
  • 1
  • 21
  • 21
  • Note: this will only give you a very rough estimate. The earth isn't a perfect sphere (which is why [WGS84](http://en.wikipedia.org/wiki/WGS84) exists) and the calculation doesn't consider height. – GrahamS May 27 '11 at 07:38
3

http://en.wikipedia.org/wiki/Great-circle_distance

(Pythagorean theorem won't be enough because of earth's sphericity)

Igor
  • 25,778
  • 27
  • 87
  • 113