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 (curr开发者_JAVA技巧ent 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?
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.
Would this be valid?
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
Thanks!
精彩评论