用于计算Haversine距离的MySQL函数

时间:2014-02-12 09:46:31

标签: mysql function distance haversine

所有

我想创建一个mysql函数来计算两个地理代码之间的半径距离。

 CREATE FUNCTION haversineDistance
                 (
                  lat1 VARCHAR(256), 
                  long1 VARCHAR(256), 
                  lat2 VARCHAR(256), 
                  long2 VARCHAR(256)
                 )
 RETURNS FLOAT DETERMINISTIC
 BEGIN

      DECLARE radLat1 FLOAT;
      DECLARE radLong1 FLOAT;
      DECLARE radLat2 FLOAT;
      DECLARE radLong2 FLOAT;
      DECLARE dLat FLOAT;
      DECLARE dLong FLOAT;
      DECLARE cordLength FLOAT;
      DECLARE centralAngle FLOAT;
      DECLARE distance FLOAT;

      SET radLat1 = CAST(lat1 AS FLOAT) * PI() / 180;
      SET radLong1 = CAST(long1 AS FLOAT) * PI() / 180;
      SET radLat2 = CAST(lat2 AS FLOAT) * PI() / 180;
      SET radLong2 = CAST(long2 AS FLOAT) * PI() / 180;
      SET dLat = radLat2 - radLat1;
      SET dLong = radLong2 - radLong2;
      SET cordLength = POW(SIN(dLat/2),2)+COS(lat1)*COS(lat2)*POW(SIN(dLon/2),2);
      SET centralAngle = 2 * ATAN2(SQRT(cordLength), SQRT(1-cordLength));
      SET distance = 6367 * centralAngle;

      RETURN distance;
 END

但是我得到了这样的错误;

  

1064 - 您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近''第4行

有人有想法吗?

提前谢谢。

2 个答案:

答案 0 :(得分:2)

好。

解决了它。

 DELIMITER $$
 CREATE FUNCTION haversineDistance
                 (
                  lat1 VARCHAR(256), 
                  long1 VARCHAR(256), 
                  lat2 VARCHAR(256), 
                  long2 VARCHAR(256))
 RETURNS FLOAT DETERMINISTIC
 BEGIN

      DECLARE radLat1 FLOAT;
      DECLARE radLong1 FLOAT;
      DECLARE radLat2 FLOAT;
      DECLARE radLong2 FLOAT;
      DECLARE dLat FLOAT;
      DECLARE dLong FLOAT;
      DECLARE cordLength FLOAT;
      DECLARE centralAngle FLOAT;
      DECLARE distance FLOAT;

      SET radLat1 = CAST(lat1 AS DECIMAL(10,10)) * PI() / 180;
      SET radLong1 = CAST(long1 AS DECIMAL(10,10)) * PI() / 180;
      SET radLat2 = CAST(lat2 AS DECIMAL(10,10)) * PI() / 180;
      SET radLong2 = CAST(long2 AS DECIMAL(10,10)) * PI() / 180;
      SET dLat = radLat2 - radLat1;
      SET dLong = radLong2 - radLong2;
      SET cordLength = POW(SIN(dLat/2),2)+COS(lat1)*COS(lat2)*POW(SIN(dLon/2),2);
      SET centralAngle = 2 * ATAN2(SQRT(cordLength), SQRT(1-cordLength));
      SET distance = 6367 * centralAngle;

      RETURN distance;
 END

答案 1 :(得分:0)

现在,由于在您的函数中将分号字符作为行分隔符,您将收到错误。

进一步解释,直接引用MySQL documentation

  

默认情况下,mysql将分号识别为语句分隔符,   所以你必须暂时重新定义分隔符以使mysql通过   整个存储的程序定义到服务器。

这意味着您必须暂时覆盖默认分隔符以便程序进行编译。

之间的程序封装
DELIMITER $$
   your code for function
$$

然后尝试一下。

编辑: 您可以通过再次指定默认分隔符来更改分隔符

mysql> DELIMITER ;