mysql根据经纬度计算距离

1:定义存储函数

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((lon1-lon2)*PI()/180/2)   
        *SIN((lon1-lon2)*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((lon1-lon2)*PI()/180/2)   
        *SIN((lon1-lon2)*PI()/180/2))))*radius;
    return d;

end


2:查询函数

// 经度 lng   // 纬度 lat

select getDistance(IFNULL(si.LNG, 0),IFNULL(si.LAT, 0), #{lng}, #{lat}) distance  from shop_info si   

你可能感兴趣的:(mysql)