• php mysql 根据经纬度计算距离和排序


    #1.两点距离(1.4142135623730951)
    select st_distance(point(0,0),point(1,1));
    select st_distance(point (120.10591, 30.30163),point(120.13026,30.25961)) as distance HAVING distance>0 ORDER BY distance;
    mysql 5.6 添加
    
    #2.两点球面距离(157249.0357231545m)
    select st_distance_sphere(point(0,0),point(1,1)) as distance HAVING distance>0 ORDER BY distance;
    select st_distance_sphere(point (120.10591, 30.30163),point(120.13026,30.25961)) as distance HAVING distance>0 ORDER BY distance;
    This function was added in MySQL 5.7.6.

    第一个函数是计算平面坐标系下,两点的距离,就是

    • formula

     如果用于计算地球两点的距离,带入的参数是角度(经纬度),则计算的单位也是相差的角度,用此角度计算距离不准。纬度距离约111km每度,经度距离在赤道平面上是111km每度,随纬度的升高逐渐降低为0。

    第二个函数是计算球面距离的公式,传入的参数是经纬度(经度-180~180,纬度-90~90),返回的值以m为单位的距离。

    ST_Distance_Sphere(g1g2 [, radius])

    如果mysql版本不支持上述函数怎么办?自己实现喽!下面是我自己写的球面距离函数

    delimiter //
    drop function if exists Spherical_Distance;
    create function Spherical_Distance(jin1 double,wei1 double,jin2 double,wei2 double) returns double
    NO SQL
    BEGIN
      declare j1 double;
      declare w1 double;
      declare j2 double;
      declare w2 double;
      declare R double;
      set j1 = jin1*PI()/180;
      set w1 = wei1*PI()/180;
      set j2 = jin2*PI()/180;
      set w2 = wei2*PI()/180;
      set R = 6370986;
      return R*acos(cos(w1)*cos(w2)*cos(j1-j2)+sin(w1)*sin(w2));        
    END
    //
    delimiter ;

    调用方式

    select Spherical_Distance(120.10591,30.30163,120.13026,30.25961);

    计算出的值和st_distance_sphere函数计算结果相差不大。

    另外的求经纬度距离方法:

      $lat = trim($_POST['lat']);
            $lng = trim($_POST['lng']);
            $distance = "
            ROUND(
            6378.138 * 2 * ASIN(
                SQRT(
                    POW(
                        SIN(
                            (
                                '$lat' * PI() / 180 - lat * PI() / 180
                            ) / 2
                        ),
                        2
                    ) + COS(40.0497810000 * PI() / 180) * COS(lat * PI() / 180) * POW(
                        SIN(
                            (
                                '$lng' * PI() / 180 - lng * PI() / 180
                            ) / 2
                        ),
                        2
                    )
                )
            ) * 1000 )  AS distance ";
            // 内容
            $sql = <<<doc
    select id,title as shop_name,create_at,master_title,lng,lat,reg_address,province,city,area,address,start_at,end_at,phone,business_name,business_phone,pics,club_id,{$distance}
    from jiazhen_shop_info as jsi
    where 1=1 order by distance ASC,id desc
    doc;    
  • 相关阅读:
    每天一个命令
    2017-2-21
    egrep []+ 和awk总结
    ifconfig eth0 取行取列
    stat /etc/hosts 取行取列644
    压缩解压缩
    目录
    公告
    To do list
    CSP 2019 游记
  • 原文地址:https://www.cnblogs.com/-mrl/p/11975922.html
Copyright © 2020-2023  润新知