The Haversine formula determines the great-circle distance between two points on a sphere given their latitudes and longitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of Haversines, that relates the sides and angles of spherical triangles.
go get https://github.com/kwahome/go-haversine
Below is an example showing how to calculate the shortest path between two coordinates on the surface of the Earth.
package main
import (
"fmt"
"github.com/kwahome/go-haversine/pkg/haversine"
)
func main() {
nairobi := haversine.Coordinate{
Latitude: 1.2921,
Longitude: 36.8219,
}
mombasa := haversine.Coordinate{
Latitude: 4.0435,
Longitude: 39.6682,
}
units := haversine.M
distance := nairobi.DistanceTo(mombasa, units)
fmt.Println("Distance from Nairobi =", nairobi, "to Mombasa =", mombasa, "in", units, "is", distance)
units = haversine.KM
distance = nairobi.DistanceTo(mombasa, units)
fmt.Println("Distance from Nairobi =", nairobi, "to Mombasa =", mombasa, "in", units, "is", distance)
units = haversine.MI
distance = nairobi.DistanceTo(mombasa, units)
fmt.Println("Distance from Nairobi =", nairobi, "to Mombasa =", mombasa, "in", units, "is", distance)
}
Distance from Nairobi = {latitude=1.2921, longitude=36.8219} to Mombasa = {latitude=4.0435, longitude=39.6682} in meters is 439923.26193980715
Distance from Nairobi = {latitude=1.2921, longitude=36.8219} to Mombasa = {latitude=4.0435, longitude=39.6682} in kilometers is 439.92326193980716
Distance from Nairobi = {latitude=1.2921, longitude=36.8219} to Mombasa = {latitude=4.0435, longitude=39.6682} in miles is 273.3034485571742
Find the entire code in the repository:
https://github.com/kwahome/go-haversine
Use convenience scripts in ./bin
to run tests and format code.
Tests:
./bin/unit_test.sh
Code formatting:
./bin/code_format.sh
https://godoc.org/github.com/kwahome/go-haversine
See the LICENSE file for license rights and limitations (MIT).