Querying MySQL for latitude and longitude coordinates that are within a given mile radius

前端 未结 1 543
遇见更好的自我
遇见更好的自我 2021-02-01 19:51

I currently have a MySQL table that is structured as follows:

id         name     lon            lat  
-----      -----    -----------    -----------
1                   


        
1条回答
  •  长情又很酷
    2021-02-01 20:46

    Spherical Law of Cosines Formula
    (37 and -122 are the latitude and longitude of your radius center)

    SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
        * cos( radians( long ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance 
    FROM myTable
    HAVING distance < 50
    ORDER BY distance 
    

    Features

    • Fastest
    • Precision similar to Harvesine Formula

    Haversine Formula

    SELECT id, 3956 * 2 * ASIN(SQRT(POWER(SIN((37 - abs(lat)) * pi()/180 / 2), 2)
           + COS(37 * pi()/180 ) * COS(abs(lat) * pi()/180)
           * POWER(SIN((-122 - long) * pi()/180 / 2), 2) )) as  distance
    FROM myTable
    HAVING distance < 50
    ORDER BY distance
    

    Features

    • Fast
    • More robust to floating point errors

    Note that 3959 is the Earth radius in miles. Earth radius in km: 6371

    You can find more information here

    0 讨论(0)
提交回复
热议问题