How to efficiently find the closest locations nearby a given location

前端 未结 4 1283
死守一世寂寞
死守一世寂寞 2020-11-27 12:07

I\'m making a script where a load of business are loaded into a mySQL database with a latitude and longitude. Then I am supplying that script with a latitude an longitude (o

4条回答
  •  一整个雨季
    2020-11-27 13:02

    I think what you're trying to achieve could be done better using the Haversine formula in your SQL. Google has a tutorial on how to get the nearest locations in a MySQL database but the general idea is this SQL:

    SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) )
      * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) 
      * sin( radians( lat ) ) ) ) AS distance
    FROM markers
    HAVING distance < 25
    ORDER BY distance LIMIT 0 , 20;
    

    Then all the work you need to do is done on the database, so you don't have to pull all the businesses into your PHP script before you even check the distance.

提交回复
热议问题