haversin.c 707 Bytes
Newer Older
saeed's avatar
saeed committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
static double DEG_TO_RAD = 0.0174532;
static double EARTH_RADIUS_IN_METERS = 6372797.560856;

struct Position {
  double lat;
  double lon;
};

static double haversine(struct Position *from, struct Position *to) {
  double lat_arc = (from->lat - to->lat) * DEG_TO_RAD;
  double lon_arc = (from->lon - to->lon) * DEG_TO_RAD;
  double lat_h   = sin(lat_arc * 0.5);
  lat_h  *= lat_h;
  double lon_h   = sin(lon_arc * 0.5);
  lon_h       *= lon_h;
  double tmp = cos(from->lat*DEG_TO_RAD) * cos(to->lat*DEG_TO_RAD);
  return (2.0 * asin(sqrt(lat_h + tmp*lon_h)));
}

static double distance_in_meters(struct Position *from, struct Position *to) {
  return EARTH_RADIUS_IN_METERS*haversine(from, to);
}