开发者

SELECT question

开发者 https://www.devze.com 2022-12-21 06:44 出处:网络
Let\'s say I have a table containing a list of cit开发者_StackOverflow社区ies: city | latitude | longitude

Let's say I have a table containing a list of cit开发者_StackOverflow社区ies:

city | latitude | longitude
---------------------------
XX   | 34.800   | 48.550

Assuming I have an approximate location (latitude/longitude) of a user, how do I find the city that is nearest? That is, how do I find the city whose latitude and longitude is closest to the user's lat/long?


Check out

Creating a Store Locator with PHP, MySQL & Google Maps

the calculation method presented there is independent from Google Maps, you should be able to get the complete algorithm from there.

One just needs to be wary of different mapping methods and the resulting different coordinates. Depending on what mapping your coordinates use, you may have to tweak the algorithm's parameters.


Google maps api has a new feature that does reverse geo caching

Have fun :)

More info on their wiki


You could use the geospatial extensions for MySQL, or

The formula below will find the distance in nautical miles between two points.

3600 * acos(sin(latitude2_rads) * sin(latitude1_rads) +cos(latitude2_rads) * cos(latitude1_rads) * cos(longitude1_rads - longitude2_rads))

So you can connect this into a select as follows (in the following -7 is the required lat and -14 is the required lon)

Assuming that the lat/lon fields are in degrees:

select * FROM NDB as c1
order by  acos(sin(radians(-7))
          * sin(radians(latitude)) + cos(radians(-7))
          * cos(radians(latitude))
          * cos(radians(longitude) - radians(-14)))
limit 0,1

This may not be very efficient with large datasets, I just ran it against a table with 22,706 records and it took 0.163seconds.

If performance is an issue then it may be better to pre-compute the distance of all points from a fixed datum and then use that instead of computing it in the SQL.

0

精彩评论

暂无评论...
验证码 换一张
取 消