现在如果有个业务需求,就是要做一个根据定位坐标实现计算距离并找到附近的店铺的推荐功能,已知数据库中会存储店铺的经纬度坐标。那么,这个需求已经很明确了,在要求不高的情况下,只要计算两个坐标的距离,进行一次排序即可。
下面会给出其中的核心代码,是某个大佬从“google maps”的脚本里扒的代码,是用来计算两点间经纬度距离,这样的计算方式得到的距离并非真实的距离,是理论上的直线距离,但其距离也已经很准确。不过毕竟是通过逻辑计算得到的距离,若要求高准确性的距离信息的话,还是借助第三方的地图api接口获取比较合适。
我将这段代码转成了golang版,并对传入的坐标进行了限制,让它更符合现实生活中的情况。
package main
import (
"fmt"
"log"
"math"
)
const (
EARTHRADIUS = 6378.137 //赤道半径
Degree = 180.0
)
//以公里为单位
func CalculateTheDistanceByCoordinate(currentLocLat, currentLocLng, intentLocLat, intentLocLng float64) (distance float64, err error) {
if currentLocLat > 90 || currentLocLat < -90 || intentLocLat > 90 || intentLocLat < -90 {
err = fmt.Errorf("illegal latitude: currentLocLat %f, intentLocLat %f\n", currentLocLat, intentLocLat)
return
}
if currentLocLng > 180 || currentLocLng < -180 || intentLocLng > 180 || intentLocLng < -180 {
err = fmt.Errorf("illegal longitude: currentLocLng %f, intentLocLng %f\n", currentLocLng, intentLocLng)
return
}
var rad = func(coordinate float64) (radian float64) {
return coordinate * math.Pi / Degree
}
differenceLocLat := rad(currentLocLat) - rad(intentLocLat)
differenceLocLng := rad(currentLocLng) - rad(intentLocLng)
distance = 2 * math.Asin(math.Sqrt(math.Pow(math.Sin(differenceLocLat/2), 2) +
math.Cos(rad(currentLocLat))*math.Cos(rad(intentLocLat))*math.Pow(math.Sin(differenceLocLng/2), 2)))
distance = math.Round(distance*EARTHRADIUS*10000) / 10000
return
}
package main
import (
"github.com/smartystreets/goconvey/convey"
"testing"
)
func TestCalculateTheDistanceByCoordinate(t *testing.T) {
convey.Convey("CalculateTheDistanceByCoordinate", t, func(c convey.C) {
c.Convey("normal", func(c convey.C) {
m, _ := CalculateTheDistanceBetweenSellerStoresByCoordinate(22.982236862182617, 113.34020233154297,
22.982236862182617, 113.34020233154297)
c.So(m, convey.ShouldBeZeroValue)
m, _ = CalculateTheDistanceBetweenSellerStoresByCoordinate(22.982236862182617, 113.34020233154297,
-15.47, -47.56)
c.So(m, convey.ShouldEqual, 17865.4643)
})
c.Convey("abnormal", func(c convey.C) {
m, err := CalculateTheDistanceBetweenSellerStoresByCoordinate(22.982236862182617, 113.34020233154297,
400, 400)
c.So(m, convey.ShouldNotBeEmpty)
c.So(err, convey.ShouldNotBeNil)
m, err = CalculateTheDistanceBetweenSellerStoresByCoordinate(22.982236862182617, 113.34020233154297,
-10, 400)
c.So(m, convey.ShouldNotBeEmpty)
c.So(err, convey.ShouldNotBeNil)
})
})
}
参考
https://www.cnblogs.com/zhoug2020/p/7634187.html
https://blog.csdn.net/zhuxiaoping54532/article/details/53671641