2011-09-20 38 views
6

我們有一個包含地點及其緯度和經度的表格。使用經度和緯度在SQL Server 2008中的兩個位置之間的返回距離

我們試圖在SQL Server 2008中創建一個函數,以特定的經度和緯度爲中心點列出未來25公里內的地點。

我是遊蕩,如果這是啓動和測試我們的功能,並得到一箇中心點之間的當前距離(當前位置)和目標位置(@緯度/ @經度)的好方法:

ALTER FUNCTION [dbo].[GetDistanceFromLocation] 
( 
    @myCurrentLatitude float, 
    @myCurrentLongitude float, 
    @latitude float, 
    @longitude float 
) 
RETURNS int 
AS 
BEGIN 
    DECLARE @radiusOfTheEarth int 
    SET @radiusOfTheEarth = 6371--km 

    DECLARE @distance int 
    SELECT @distance = (@radiusOfTheEarth 
     * acos(cos(radians(@myCurrentLatitude)) 
     * cos(radians(@latitude)) 
     * cos(radians(@longitude) - radians(@myCurrentLongitude)) + sin(radians(@myCurrentLatitude)) 
     * sin(radians(@latitude)))) 

    RETURN @distance 

END 

這是正確的還是我們錯過了什麼?

回答

11

它看起來像你使用great-circle distance公式,這可能是足夠準確的,雖然你必須是這個判斷。

如果要檢查你的公式的結果,你可以使用geography數據類型:

declare @geo1 geography = geography::Point(@lat1, @long1, 4326), 
     @geo2 geography = geography::Point(@lat2, @long2, 4326) 

select @geo1.STDistance(@geo2) 

因爲你正在做一個proximity search,你可能要調查geography數據類型進一步。

+0

什麼是4326?我試圖看到MSDN,但沒有任何有關它的信息。 –

+0

4326是世界大地測量參考系統的空間參考ID。有關更多信息,請參閱http://technet.microsoft.com/en-us/library/bb933811.aspx http://en.wikipedia.org/wiki/SRID和http://en.wikipedia.org/wiki/WGS84 –

0

這是有效的嗎?

CREATE FUNCTION [dbo].[GetDistanceFromLocation] 
( 
    @CurrentLatitude float, 
    @CurrentLongitude float, 
    @latitude float, 
    @longitude float 
) 
RETURNS int 
AS 
BEGIN 
    DECLARE @geo1 geography = geography::Point(@lat1, @long1, 4268), 
      @geo2 geography = geography::Point(@lat2, @long2, 4268) 

    DECLARE @distance int 
    SELECT @distance = @geo1.STDistance(@geo2) 

    RETURN @distance 

END 

謝謝!

+0

歡迎來到Stack Overflow!這真是一個評論,而不是一個答案。有了更多的代表,[你將能夠發表評論](// stackoverflow.com/privileges/comment)。我將這個帖子標記爲刪除。 –

相關問題