1. 程式人生 > 其它 >SQL Server--查詢附近的酒店

SQL Server--查詢附近的酒店

問題描述:

根據手機上已知的客戶經緯度座標,查詢5公里範圍內的酒店。

在《酒店資訊表》中有經度和緯度兩個欄位儲存酒店座標,計算客戶座標與酒店座標之間的距離,返回5公里內的所有酒店資訊。

 

程式碼實現:

create function fnGetDistance (@LatBegin real, @LngBegin real, @LatEnd real, @LngEnd real)
returns float
as
begin
declare @del_lat float, @del_lng float, @factor float, @distance float
select @factor = pi()/180  -- 將角度轉換為弧度,不清楚資料的格式,或許不需要轉換
select @del_lat = @LatEnd - @LatBegin  -- 兩點間緯度差
select @del_lng = @LngEnd - @LngBegin  -- 兩點間經度差
select @distance = 6378.137*2*asin(sqrt(square(sin(@del_lat*@factor/2))+cos(@LatBegin*@factor)*cos(@LatEnd*@factor)*square(sin(@del_lng*@factor/2))))
  -- 半正矢公式,單位為km
return(@distance)
end
go

declare @Lat0 real, @Lng0 real, @Lat1 real, @Lng1 real, @distance float, @i float
select @Lat0 = 30
select @Lng0 = 114  --起點經緯度
select @i = 0
declare Cursor_hotel cursor
  for select Latitude, Longitude from Hotel
open Cursor_hotel
fetch next from Cursor_hotel
  into @Lat1, @Lng1
while @@fetch_status = 0
  begin
  exec @distance = fnGetDistance @Lat0, @Lng0, @Lat1, @Lng1
  if @distance <= 5
    begin
    @i = @i +1
    print '找到第'+ltrim(str(@i))+'個5公里內酒店的緯度和經度為:'+str(@Lat1)+' , '+str(@Lng1)
    end
  fetch next from Cursor_hotel
    into @Lat1, @Lng1
  end
if @i = 0
  print '很抱歉,沒有找到5公里內的酒店!'
close Cursor_hotel
deallocate Cursor_hotel
go