Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return distance between two locations in SQL Server 2008 using latitude and longitude

We have a table with places and their latitudes and longitudes.

We are trying to create a function in SQL Server 2008 to list places within next 25 kilometers using a specific latitude and longitude as centre point.

I was wandering if this is a good way to start and test our function and getting current distance between a centre point (current location) and a target location (@latitude/@longitude):

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

Is it correct or we are missing something?

like image 997
Junior Mayhé Avatar asked Sep 20 '11 17:09

Junior Mayhé


1 Answers

It looks like you are using the great-circle distance formula, which is probably accurate enough for you, although you'll have to be the judge of that.

If you want to check the results of your formula, you can use the geography data type:

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

select @geo1.STDistance(@geo2)

and since you are doing a proximity search, you may want to investigate the geography data type further.

like image 92
Jeff Ogata Avatar answered Nov 15 '22 06:11

Jeff Ogata