MySQL 函数-根据经纬度坐标计算距离

MySQL 数据库获取两点经纬度的距离,封装成Functions,代码如下:


DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `get_distance`(curLat DOUBLE, curLon DOUBLE, srcLat DOUBLE, srcLon DOUBLE) RETURNS double
BEGIN  

  DECLARE dis DOUBLE;  
  DECLARE radius INT;
  SET radius = 180;
  
  SET curLat = IFNULL(curLat,0.0);
  SET curLon = IFNULL(curLon,0.0);
  SET srcLat = IFNULL(srcLat,0.0);
  SET srcLon = IFNULL(srcLon,0.0);
  
  set dis = ACOS(SIN((curLat * PI()) / radius ) * SIN((srcLat * PI()) / radius ) + COS((curLat * PI()) / radius ) * COS((srcLat * PI()) / radius ) * COS((curLon * PI()) / radius - (srcLon * PI()) / radius ) ) * 6378.137;  
  ##FORMAT(dis,1);
  RETURN  dis;
  
  END

DELIMITER ;


得到的距离单位是公里数


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。