Skip to content

Instantly share code, notes, and snippets.

@DeanThompson
Last active August 29, 2015 14:08
Show Gist options
  • Save DeanThompson/e04306e30d7566734516 to your computer and use it in GitHub Desktop.
Save DeanThompson/e04306e30d7566734516 to your computer and use it in GitHub Desktop.
calculate distance in meters between two given location point
package main
import (
"math"
)
const (
RAD_FACTOR = math.Pi / 180.0
EARTH_RADIUS = 6371000
)
func FloatEquals(fa, fb float64) bool {
return math.Abs(fa-fb) < 0.000001
}
// Calculate the distance in meters between two given location point
func Distance(lat1, lng1, lat2, lng2 float64) int {
if FloatEquals(lat1, lat2) && FloatEquals(lng1, lng2) {
return 0
}
lat1 *= RAD_FACTOR
lng1 *= RAD_FACTOR
lat2 *= RAD_FACTOR
lng2 *= RAD_FACTOR
distance := math.Acos(math.Sin(lat1)*math.Sin(lat2) + math.Cos(lat1)*math.Cos(lat2)*math.Cos(lng2-lng1))
return int(distance * EARTH_RADIUS)
}
func main() {
lat := 28.418101
lng := 119.060573
lat1 := 29.418101
lng1 := 120.34423
fmt.Println(Distance(lat, lng, lat1, lng1)) // output: 167251
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment