Mysql数据库中计算两GPS坐标的距离有两种方式:
1、直接使用SQL语句:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#lat为纬度, lng为经度, 一定不要弄错
declare @lng1 float;
declare @lat1 float;
declare @lng2 float;
declare @lat2 float;
set @lng1=116.3899;
set @lat1=39.91578;
set @lng2=116.3904;
set @lat2=39.91576; 
select (2*ATAN2(SQRT(SIN((@lat1-@lat2)*PI()/180/2)  
        *SIN((@lat1-@lat2)*PI()/180/2)+  
        COS(@lat2*PI()/180)*COS(@lat1*PI()/180)  
        *SIN((@lng1-@lng2)*PI()/180/2)  
        *SIN((@lng1-@lng2)*PI()/180/2)),  
        SQRT(1-SIN((@lat1-@lat2)*PI()/180/2)  
        *SIN((@lat1-@lat2)*PI()/180/2)  
        +COS(@lat2*PI()/180)*COS(@lat1*PI()/180)  
        *SIN((@lng1-@lng2)*PI()/180/2)  
        *SIN((@lng1-@lng2)*PI()/180/2))))*6378140;
#返回结果: 42.7484246368099


2、定义函数后再调用(适合批量计算):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# use aiezu;
drop function getDistance;
DELIMITER $$ 
CREATE DEFINER=`root`@`localhost` FUNCTION `getDistance`(
     lng1 float(10,7)
    ,lat1 float(10,7)
    ,lng2 float(10,7)
    ,lat2 float(10,7)
RETURNS double
begin
    declare double;
    declare radius int;
    set radius = 6378140; #假设地球为正球形,直径为6378140米
    set d = (2*ATAN2(SQRT(SIN((lat1-lat2)*PI()/180/2)  
        *SIN((lat1-lat2)*PI()/180/2)+  
        COS(lat2*PI()/180)*COS(lat1*PI()/180)  
        *SIN((lng1-lng2)*PI()/180/2)  
        *SIN((lng1-lng2)*PI()/180/2)),  
        SQRT(1-SIN((lat1-lat2)*PI()/180/2)  
        *SIN((lat1-lat2)*PI()/180/2)  
        +COS(lat2*PI()/180)*COS(lat1*PI()/180)  
        *SIN((lng1-lng2)*PI()/180/2)  
        *SIN((lng1-lng2)*PI()/180/2))))*radius;
    return d;
end
$$
DELIMITER ;
select getDistance(116.3899,39.91578,116.3904,39.91576); #调用函数
#返回结果:43.045058294389

 
常见问题及解决方法:
常见问题:
  在创建函数前报如下错误:

1
This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)

解决方法:
  在创建函数前执行下面SQL语句:

1
set global log_bin_trust_function_creators=1;

或者修改my.cnf文件并重启mysqld服务:

1
log_bin_trust_function_creators=1


PHP计算两个GPS坐标点之间的距离: http://aiezu.com/article/18.html
Javascript计算两个GPS坐标的距离: http://aiezu.com/article/17.html


标签: none

添加新评论