地理位置

计算距离

语法

对于两坐标(a,b),(c,d),距离计算如下

1
2
3
4
5
st_distance(POINT(a,b),POINT(c,d))*111195
st_distance_sphere(POINT(a,b),POINT(c,d))

--eg 找到坐标(121.59034,31.38808) 一公里以内的坐标点
select id,lon,lan,st_distance_sphere(POINT(lon,lan),POINT(121.59034,31.38808)) distant from t_test hanving distant < 1000

说明

MySQL支持地理位置的计算及查询,其主要通过 st_distancest_distance_sphere 两个函数来实现的

  • st_distance 计算两个坐标之间的弧度,如果要转换成米,则需要乘111195(地球半径6371000*PI/180)
  • st_distance_sphere 计算连个坐标之间在圆上的距离,单位米

需要注意的是两个计算的结果是不同的,原因是不同的纬度每一度的长度不相同,就导致了弧度不一致

分别拿 (1,1),(2,2) 间隔1度((121.59034, 31.38808),(121.59035, 31.38809) 间隔约一米 两个坐标举例

1
2
3
4
5
6
SELECT st_distance(POINT(1,1),POINT(2,2))*111195 AS distant from dual;    -- 得到结果  157253.47706807632 米
SELECT st_distance_sphere(POINT(1,1),POINT(2,2))) AS distant from dual; -- 得到结果 157225.08654191086 米

SELECT st_distance(POINT(121.59034, 31.38808),POINT(121.59035, 31.38809))*111195 AS distant from dual; -- 得到结果 1.5725347709005688 米
SELECT st_distance_sphere(POINT(121.59034, 31.38808),POINT(121.59035, 31.38809)) AS distant from dual; -- 得到结果 1.4620024259505242 米

根据第三四对比可以看出来,间隔1米st_distance_sphere更接近 $\sqrt[]2$ =1.414213562373095

引用