使用纬度和经度返回SQL Server 2008中两个位置之间的距离

Jun*_*r M 6 location function 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
Run Code Online (Sandbox Code Playgroud)

这是正确的还是我们遗漏了什么?

Jef*_*ata 11

看起来你正在使用大圆距离公式,这对你来说可能足够准确,尽管你必须做出判断.

如果要检查公式的结果,可以使用地理数据类型:

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

select @geo1.STDistance(@geo2)
Run Code Online (Sandbox Code Playgroud)

并且由于您正在进行邻近搜索,因此您可能希望进一步调查geography数据类型.