PHP/MySQL: Select locations close to a given location from DB

后端 未结 7 1676
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 03:15

In PHP, I have the following code for calculating the distance between two locations:



        
7条回答
  •  忘了有多久
    2021-02-02 03:48

    Just came a cross this topic. Maybe someone will be interested in this function, tested in MySql 5.7:

        create function GetDistance(lat1 real, lng1 real, lat2 real, lng2 real) returns real no sql
        return ATAN2(SQRT(POW(COS(RADIANS(lat2)) * SIN(RADIANS(lng1 - lng2)), 2) + 
                    POW(COS(RADIANS(lat1)) * SIN(RADIANS(lat2)) - SIN(RADIANS(lat1)) *
                    COS(RADIANS(lat2)) *  COS(RADIANS(lng1 - lng2)), 2)), 
                    (SIN(RADIANS(lat1)) * SIN(RADIANS(lat2)) + COS(RADIANS(lat1)) *
                    COS(RADIANS(lat2)) * COS(RADIANS(lng1 - lng2)))) * 6372.795;
    

    Calling:

    select GetDistance(your_latitude, your_longitude, table_field_lat,
                       table_field_lng) as dist from [your_table] limit 5;
    

提交回复
热议问题