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

6

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


可以回答自己的问题,但你需要先提出一个问题。你还需要解释一下你所做的假设。例如,你可能是用英里而不是公里来表示距离。看起来你的坐标是用度数表示的。你的函数文档应该说明这一点。你还假设地球是一个球体而不是椭球体。 - Jonathan Leffler
2
@SashiKant 我编辑了这篇帖子,让它成为一个我回答的问题。 - jpgunter
@JonathanLeffler 我把它改成了一个带有我的答案和文档的问题。 - jpgunter
1个回答

11

在搜索了一段时间后,我放弃了并自己编写了代码。我能够将一些其他的代码适应为以下的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 ;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接