2011-09-20 35 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)。我将这个帖子标记为删除。 –

相关问题