MySQL函数计算两个经纬度之间的距离

标签 mysql geolocation

<分区>

如果您的数据库中存储了纬度和经度,并且需要计算两个坐标之间的距离。如何使用 MySQL 函数计算它?

最佳答案

找了半天,放弃了,自己写了。我能够将一些其他代码改编为以下 MySQL 函数。

DELIMITER $$
/*
Takes two latitudes and longitudes in degrees. You could comment out the conversion if you want to pass as radians.
Calculate the distance in miles, change the radius to the earth's radius in km to get km.
*/

DROP FUNCTION IF EXISTS GETDISTANCE$$
CREATE FUNCTION GETDISTANCE 
  (deg_lat1 FLOAT, deg_lng1 FLOAT, deg_lat2 FLOAT, deg_lng2 FLOAT) 
  RETURNS FLOAT 
  DETERMINISTIC 
BEGIN 
  DECLARE distance FLOAT;
  DECLARE delta_lat FLOAT; 
  DECLARE delta_lng FLOAT; 
  DECLARE lat1 FLOAT; 
  DECLARE lat2 FLOAT;
  DECLARE a FLOAT;

  SET distance = 0;

  /*Convert degrees to radians and get the variables I need.*/
  SET delta_lat = radians(deg_lat2 - deg_lat1); 
  SET delta_lng = radians(deg_lng2 - deg_lng1); 
  SET lat1 = radians(deg_lat1); 
  SET lat2 = radians(deg_lat2); 

  /*Formula found here: http://www.movable-type.co.uk/scripts/latlong.html*/
  SET a = sin(delta_lat/2.0) * sin(delta_lat/2.0) + sin(delta_lng/2.0) * sin(delta_lng/2.0) * cos(lat1) * cos(lat2); 
  SET distance = 3956.6 * 2 * atan2(sqrt(a),  sqrt(1-a)); 

  RETURN distance;
END$$
DELIMITER ;

关于MySQL函数计算两个经纬度之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13716313/

相关文章:

php - 单击下载按钮时,如何将 MySQL 数据库中的值保存到 .txt 文件中?

Mac OS X 上的 Mysql Workbench 不显示结果网格

ios - 位置管理器区域监控

mysql - 子查询一直出错我该怎么办?

php - 如何在数据表中重音中和后在数据库中进行 jquery 搜索 - 不起作用

php - 如何解析谷歌地图地理编码结果

java - 查找我当前在 Java 中的职位

geolocation - 插件命令已重命名

mysql - 用另一个表的另一列的数据更新一列

iphone - 如何在 uiimagepickercontroller 中写入/获取图像的纬度经度?