[SQL] 利用坐標找出指定距離內的記錄

這陣子要做有關在地服務 (Location-based Service)的程式, 需要計算指定距離內的東西.

經過一輪google,找到部份指引. 原來要利用 Haversine Formula 找出. 詳細我也似非而是地理解作利用畢氐定理及asin 計出來.

結果如下:

SELECT *, (3959 * acos( cos( radians(<Current Latitude>) ) * cos( radians(<Latitude column>) ) * cos( radians(<Longitude column>) - radians(<Current Longitude>) ) + sin( radians(<Current Latitude>) ) * sin( radians( <Latitude column> ) ) ) ) AS distance 
FROM markers HAVING distance <= <Search Range> 
ORDER BY distance;

3359 是常數(Constance), 即是地球的半徑, 因為它以坐標作單位, 並靠這個換算距離. 若用公里(km) 作單位的話, 只須將這個常數轉為6371 便可.

有興趣可以自行參閱.

Reference:

http://www.movable-type.co.uk/scripts/latlong.html
https://developers.google.com/maps/articles/phpsqlsearch_v3

 

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.