mysql根据经纬度求两地距离
#1.两点距离(1.4142135623730951) select st_distance(point(0,0),point(1,1)); select st_distance(point (120.10591, 30.30163),point(120.13026,30.25961));
mysql 5.6 添加 #2.两点球面距离(157249.0357231545m) select st_distance_sphere(point(0,0),point(1,1)); select st_distance_sphere(point (120.10591, 30.30163),point(120.13026,30.25961));
This function was added in MySQL 5.7.6.
第一个函数是计算平面坐标系下,两点的距离,就是
如果用于计算地球两点的距离,带入的参数是角度(经纬度),则计算的单位也是相差的角度,用此角度计算距离不准。纬度距离约111km每度,经度距离在赤道平面上是111km每度,随纬度的升高逐渐降低为0。
第二个函数是计算球面距离的公式,传入的参数是经纬度(经度-180~180,纬度-90~90),返回的值以m为单位的距离。
ST_Distance_Sphere(
g1
, g2
[, radius
])
如果mysql版本不支持上述函数怎么办?自己实现喽!下面是我自己写的球面距离函数
delimiter // drop function if exists Spherical_Distance; create function Spherical_Distance(jin1 double,wei1 double,jin2 double,wei2 double) returns double NO SQL BEGIN declare j1 double; declare w1 double; declare j2 double; declare w2 double; declare R double; set j1 = jin1*PI()/180; set w1 = wei1*PI()/180; set j2 = jin2*PI()/180; set w2 = wei2*PI()/180; set R = 6370986; return R*acos(cos(w1)*cos(w2)*cos(j1-j2)+sin(w1)*sin(w2)); END // delimiter ;
调用方式
select Spherical_Distance(120.10591,30.30163,120.13026,30.25961);
计算出的值和st_distance_sphere函数计算结果相差不大。