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.

下面函数是计算球面距离的公式,传入的参数是经纬度(经度-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函数计算结果相差不大。

©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页