Mysql计算两GPS坐标的距离函数:

PHP计算两个GPS点之间的距离 Mysql计算两GPS坐标的距离 javascript计算两个GPS点之间的距离

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 d 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); #调用函数

Mysql计算两GPS坐标的距离SQL语句:

#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;
更多关于GPS计算请参考:http://www.movable-type.co.uk/scripts/latlong.html
错误及解决方法:
在创建函数前报如下错误:
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语句:

set global log_bin_trust_function_creators=1;

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

log_bin_trust_function_creators=1