yats.git

ref: 5640e4dfb173199c928e86b0ff0d3f0649be6543

server/geo/distances.go


 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
package geo

import "math"

type coordinate struct {
	lat float64
	lon float64
}

// haversin(θ) function
func hsin(theta float64) float64 {
	return math.Pow(math.Sin(theta/2), 2)
}

// Distance function returns the distance (in meters) between two points of
//
//	a given longitude and latitude relatively accurately (using a spherical
//	approximation of the Earth) through the Haversin Distance Formula for
//	great arc distance on a sphere with accuracy for small distances
//
// point coordinates are supplied in degrees and converted into rad. in the func
//
// distance returned is meters
// http://en.wikipedia.org/wiki/Haversine_formula
func Distance(coordinate1, coordinate2 coordinate) float64 {
	// convert to radians
	// must cast radius as float to multiply later

	var la1, lo1, la2, lo2, r float64
	la1 = coordinate1.lat * math.Pi / 180
	lo1 = coordinate1.lon * math.Pi / 180
	la2 = coordinate2.lat * math.Pi / 180
	lo2 = coordinate2.lon * math.Pi / 180

	r = 6378100 // Earth radius in meters

	// calculate
	h := hsin(la2-la1) + math.Cos(la1)*math.Cos(la2)*hsin(lo2-lo1)

	return 2 * r * math.Asin(math.Sqrt(h))
}