【Golang】计算两个地理坐标之间的距离

Calandra ·
更新时间:2024-11-14
· 602 次阅读

package main import ( "fmt" "math" ) // 球面距离公式:https://baike.baidu.com/item/%E7%90%83%E9%9D%A2%E8%B7%9D%E7%A6%BB%E5%85%AC%E5%BC%8F/5374455?fr=aladdin // GeoDistance 计算地理距离,依次为两个坐标的纬度、经度、单位(默认:英里,K => 公里,N => 海里) func GeoDistance(lng1 float64, lat1 float64, lng2 float64, lat2 float64, unit ...string) float64 { const PI float64 = 3.141592653589793 radlat1 := float64(PI * lat1 / 180) radlat2 := float64(PI * lat2 / 180) theta := float64(lng1 - lng2) radtheta := float64(PI * theta / 180) dist := math.Sin(radlat1)*math.Sin(radlat2) + math.Cos(radlat1)*math.Cos(radlat2)*math.Cos(radtheta) if dist > 1 { dist = 1 } dist = math.Acos(dist) dist = dist * 180 / PI dist = dist * 60 * 1.1515 if len(unit) > 0 { if unit[0] == "K" { dist = dist * 1.609344 } else if unit[0] == "N" { dist = dist * 0.8684 } } return dist } func main() { fmt.Printf("%f 公里", GeoDistance(120.090564, 30.344981, 120.11638, 30.2959, "K")) }
作者:神以灵



地理坐标 golang 地理

需要 登录 后方可回复, 如果你还没有账号请 注册新账号