Mysql within distance query

半腔热情 提交于 2019-12-19 03:25:25

问题


Options

$lat = '25.7742658';
$lng = '-80.1936589';
$miles = 30;

Query

SELECT *, 
   ( 3959 * acos( cos( radians($lat) ) 
   * cos( radians( lat ) ) 
   * cos( radians( lng ) - radians($lng) ) 
   + sin( radians($lat) ) 
   * sin( radians( lat ) ) ) ) AS distance 
FROM locations 
HAVING distance < $miles 
ORDER BY distance 
LIMIT 0, 20

I have a database table with 4 columns:

  • unique id
  • city name
  • latitude (lat)
  • longitude (lng)

I'm using the query on top to return locations that are within a specified number of miles from the specified coordinates. It seems to work but I'm not sure how accurate it is. I'm curios to know whether the query is good or if you have a better solution.


回答1:


that looks like the correct great circle distance query.

what are you concerned with wrt accuracy?




回答2:


if you want calculate distance from to point or find nearly place to one pointin mysql, you can use "MySQL Spatial Functions", but it is enable in MySQL 5.6. for more information you can read this article:

https://www.percona.com/blog/2013/10/21/using-the-new-mysql-spatial-functions-5-6-for-geo-enabled-applications/

or this PDF:

http://www.arubin.org/files/geo_search.pdf



来源:https://stackoverflow.com/questions/6574599/mysql-within-distance-query

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