-
Notifications
You must be signed in to change notification settings - Fork 1
/
distance.js
63 lines (48 loc) · 1.66 KB
/
distance.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
This script is pretty basic, but if you use it, please let me know. Thanks!
Andrew Hedges, andrew(at)hedges(dot)name
*/
var Rm = 3961; // mean radius of the earth (miles) at 39 degrees from the equator
var Rk = 6373; // mean radius of the earth (km) at 39 degrees from the equator
/* main function */
function findDistance(cor1,cor2) {
var t1, n1, t2, n2, lat1, lon1, lat2, lon2, dlat, dlon, a, c, dm, dk, mi, km;
// get values for lat1, lon1, lat2, and lon2
//t1 = frm.lat1.value;
t1 = cor1.latitude;
//n1 = frm.lon1.value;
n1 = cor1.longitude;
//t2 = frm.lat2.value;
t2 = cor2.latitude;
//n2 = frm.lon2.value;
n2 = cor2.longitude;
// convert coordinates to radians
lat1 = deg2rad(t1);
lon1 = deg2rad(n1);
lat2 = deg2rad(t2);
lon2 = deg2rad(n2);
// find the differences between the coordinates
dlat = lat2 - lat1;
dlon = lon2 - lon1;
// here's the heavy lifting
a = Math.pow(Math.sin(dlat/2),2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2),2);
c = 2 * Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); // great circle distance in radians
dm = c * Rm; // great circle distance in miles
dk = c * Rk; // great circle distance in km
// round the results down to the nearest 1/1000
mi = round(dm);
km = round(dk);
// display the result
// frm.mi.value = mi;
//frm.km.value = km;
return km;
}
// convert degrees to radians
function deg2rad(deg) {
rad = deg * Math.PI/180; // radians = degrees * pi/180
return rad;
}
// round to the nearest 1/1000
function round(x) {
return Math.round( x * 1000) / 1000;
}