#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.
第一個函數是計算平面座標系下,兩點的距離,就是html
若是用於計算地球兩點的距離,帶入的參數是角度(經緯度),則計算的單位也是相差的角度,用此角度計算距離不許。緯度距離約111km每度,經度距離在赤道平面上是111km每度,隨緯度的升高逐漸下降爲0。mysql
第二個函數是計算球面距離的公式,傳入的參數是經緯度(經度-180~180,緯度-90~90),返回的值以m爲單位的距離。sql
ST_Distance_Sphere(
函數g1
, g2
[, radius
])
若是mysql版本不支持上述函數怎麼辦?本身實現嘍!下面是我本身寫的球面距離函數spa
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 ;
調用方式code
select Spherical_Distance(120.10591,30.30163,120.13026,30.25961);
計算出的值和st_distance_sphere函數計算結果相差不大。orm