用Go编写的地理坐标和距离库(附实例)

865 阅读1分钟

Go-geo

Go Reference

用Go编写的地理坐标和距离库。

表示坐标

myLocation := geo.Coordinate{
    Latitude: 39.7684426,
    Longitude: -86.1583112,
}

计算距离

a := geo.Coordinate{
    Latitude: 39.7684426,
    Longitude: -86.1583112,
}
b := geo.Coordinate{
    Latitude: 38.3531417,
    Longitude: -81.6388193,
}

// Two ways of calculating the distance:
distance := a.DistanceTo(b)
distance := geo.DistanceBetween(a, b)

fmt.Println("Distance is: ", distance)

// Prints:
// --> 420.6896449044601km

(注:最后的例子是420.69公里,完全是个意外,但我不会改变它)

使用geo.Distance

geo.Distance 类型表示地理空间中的距离。为了方便,可以使用一些预定义的常数:

geo.Millimeter
geo.Centimeter
geo.Meter
geo.Kilometer
geo.Mile

你可以像这样构建距离:

twoMiles := 2 * geo.Mile
tenKm := 10 * geo.Kilometer

你也可以获取以任何单位表示的距离的float64 转换:

// Construct a distance (type geo.Distance)
distance := 15 * geo.Mile

// Get the equivalent number of kilometers (type float64)
inKilometers := distance.Kilometers()

在上面的例子中,inKilometers 的值等于24.14015969842181 ,它是等于15英里的公里数。