前些天客戶提出一個這樣的要求:一個手機訂餐網,查詢當前所在位置的5公里范圍的酒店,然后客戶好去吃飯。
拿到這個請求后,不知道如何下手,靜靜地想了一下,在酒店的表中增加兩個字段,用來存儲酒店所在的經度和緯度,當訂餐的時候,要求手機得到當前客戶所在的經度和緯度傳過來,再與數據庫中酒店的經度和緯度計算一下,就查出來。
為了在數據庫中查詢兩點之間的距離,所以這個函數需要在數據庫中定義。
我網上找了很久,卻沒有找到這個函數。最后在CSDN上,一個朋友的幫助下解決了這個問題,非常感謝lordbaby給我提供這個函數,我把這個函數放到這里來,以便幫助更多許要的朋友。
--計算地球上兩個坐標點(經度,緯度)之間距離sql函數 --作者:lordbaby --整理:www.aspbc.com CREATE FUNCTION [dbo].[fnGetDistance](@LatBegin REAL, @LngBegin REAL, @LatEnd REAL, @LngEnd REAL) RETURNS FLOAT AS BEGIN --距離(千米) DECLARE @Distance REAL DECLARE @EARTH_RADIUS REAL SET @EARTH_RADIUS = 6378.137 DECLARE @RadLatBegin REAL,@RadLatEnd REAL,@RadLatDiff REAL,@RadLngDiff REAL SET @RadLatBegin = @LatBegin *PI()/180.0 SET @RadLatEnd = @LatEnd *PI()/180.0 SET @RadLatDiff = @RadLatBegin - @RadLatEnd SET @RadLngDiff = @LngBegin *PI()/180.0 - @LngEnd *PI()/180.0 SET @Distance = 2 *ASIN(SQRT(POWER(SIN(@RadLatDiff/2), 2)+COS(@RadLatBegin)*COS(@RadLatEnd)*POWER(SIN(@RadLngDiff/2), 2))) SET @Distance = @Distance * @EARTH_RADIUS --SET @Distance = Round(@Distance * 10000) / 10000 RETURN @Distance END
--經度 Longitude 簡寫Lng, 緯度 Latitude 簡寫Lat --跟坐標距離小於5公里的數據 SELECT * FROM 商家表名 WHERE dbo.fnGetDistance(121.4625,31.220937,longitude,latitude) < 5
這里的longitude,latitude分別是酒店的經度和緯度字段,而121.4625,31.220937是手機得到的當前客戶所在的經度,后面的5表示5公里范圍之內。
JS版本
function toRadians(degree) { return degree * Math.PI / 180; } function distance(latitude1, longitude1, latitude2, longitude2) { // R is the radius of the earth in kilometers var R = 6371; var deltaLatitude = toRadians(latitude2-latitude1); var deltaLongitude = toRadians(longitude2-longitude1); latitude1 =toRadians(latitude1); latitude2 =toRadians(latitude2); var a = Math.sin(deltaLatitude/2) * Math.sin(deltaLatitude/2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(deltaLongitude/2) * Math.sin(deltaLongitude/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d; }