From 980a2f38d32189ff3b0fee805752ef39e9a58bb0 Mon Sep 17 00:00:00 2001 From: Patrick Peng Sun Date: Fri, 28 Apr 2017 00:16:03 +1000 Subject: [PATCH] added function to calculate distance between two point of earth, in meters, from Github gist --- calDistance.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 calDistance.go diff --git a/calDistance.go b/calDistance.go new file mode 100644 index 0000000..494a15f --- /dev/null +++ b/calDistance.go @@ -0,0 +1,34 @@ +package main + +import "math" + +// 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(lat1, lon1, lat2, lon2 float64) float64 { + // convert to radians + // must cast radius as float to multiply later + var la1, lo1, la2, lo2, r float64 + la1 = lat1 * math.Pi / 180 + lo1 = lon1 * math.Pi / 180 + la2 = lat2 * math.Pi / 180 + lo2 = lon2 * 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)) +}