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

一个人想着一个人 提交于 2019-12-03 03:58:23
Tech Savant

Spherical Law of Cosines Formula
(37 and -122 are the lat and lon 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!