Last active
March 9, 2017 16:46
-
-
Save durp/d1fad21d4d34c7bb4ace800873195c6f to your computer and use it in GitHub Desktop.
Haversine [Go]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "math" | |
type Vertex struct { | |
Lat, Long float64 | |
} | |
var m = map[string]Vertex{ | |
"Bell Labs":{40.68433, -74.39967}, | |
"Google":{37.42202, -122.08408}, | |
} | |
func main() { | |
fmt.Println(m) | |
fmt.Printf("Distance: %fm", haversine(m["Bell Labs"], m["Google"])) | |
} | |
func toRadians(deg float64) float64 { | |
return deg * math.Pi / 180.0 | |
} | |
func haversine(v1 Vertex, v2 Vertex) float64 { | |
R := 6371e3 // Earth mean radius in meters | |
ɸ1 := toRadians(v1.Lat) | |
ɸ2 := toRadians(v2.Lat) | |
Δɸ := toRadians(v2.Lat - v1.Lat) | |
Δλ := toRadians(v2.Long - v1.Long) | |
a := math.Sin(Δɸ/2) * math.Sin(Δɸ/2) + | |
math.Cos(ɸ1) * math.Cos(ɸ2) * | |
math.Sin(Δλ/2) * math.Sin(Δλ/2) | |
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) | |
return R * c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment