go语言使用Haversine公式计算两个坐标之间的距离
Go  /  管理员 发布于 2星期前   202
根据坐标计算当前位置到附近一个点或多个点的距离,我们就可以使用Haversine公式了。
下面是一个使用Haversine公式计算两个坐标之间距离功能的代码示例:
package controllers
import (
"fmt"
"math"
)
// TestController is a test control
type TestController struct {
//beego.Controller
BaseController
}
//坐标-经纬度
type Coordinates struct {
Latitude float64
Longitude float64
}
//地球的平均半径以千米为单位
const radius = 6371
//度数转弧度公式
func degrees2radians(degrees float64) float64 {
return degrees * math.Pi / 180
}
//Haversine公式(半正矢公式):计算两点之间的直线距离
func (origin Coordinates) Distance(destination Coordinates) float64 {
degreesLat := degrees2radians(destination.Latitude - origin.Latitude)
degreesLong := degrees2radians(destination.Longitude - origin.Longitude)
a := (math.Sin(degreesLat/2)*math.Sin(degreesLat/2) +
math.Cos(degrees2radians(origin.Latitude))*
math.Cos(degrees2radians(destination.Latitude))*math.Sin(degreesLong/2)*
math.Sin(degreesLong/2))
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
d := radius * c
return d
}
func (c *TestController) Aaa() {
//广州 - 天河公园
pointA := Coordinates{23.127613278533207, 113.36619463562009}
//广州 - 骏唐购物广场
pointB := Coordinates{23.125876748465735, 113.38340368865964}
fmt.Println("广州-天河公园 A : ", pointA)
fmt.Println("广州-骏唐购物广场 B : ", pointB)
distance := pointA.Distance(pointB)
fmt.Printf("广州-天河公园到广州-骏唐购物广场的距离是 %.2f 公里.\n", distance)
}
效果图:
nkt 在
阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 用了三分钟就被禁了,直接阿里云服务器22端口都禁了..熊丽 在
安装docker + locust + boomer压测环境实现对接口的压测中评论 试试水..博主 在
阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 @test 也可能是国内大环境所至,也是好事,督促你该研究学习新技术..test 在
阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 打了一次网页,然后再也打不开了。。是阿里云的缘故吗?..博主 在
centos7中Meili Search搜索引擎安装流程步骤中评论 @鹿 执行以下命令看看你的2.27版本是否存在strin..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号