>This gives results that may be farther away
> (1) The longitude (or was it the latitude) varies. ie the distance of one degree depends on where you are
>(2) the between clause gives the locations in a rectangle. You need the circle in the rectangle with a radius of SearchDistance since the corners of the rectangle will have a distance that is greater than SearchDistance
>
>You need to apply a final where clause
>
>where ,,,,
> and calculatedDistance < = SearchDistance
Adjusting the query like this would include the calculated distance:
declare @CenterLat float=47.7795
declare @CenterLon float=-65.7191
declare @SearchDistance float=250
declare @EarthRadius float=6371
declare @CntXAxis float
declare @CntYAxis float
declare @CntZAxis float
set @CntXAxis = cos(radians(@CenterLat)) * cos(radians(@CenterLon))
set @CntYAxis = cos(radians(@CenterLat)) * sin(radians(@CenterLon))
set @CntZAxis = sin(radians(@CenterLat))
select test2.*
from (
select *, calculatedDistance = @EarthRadius * acos( XAxis*@CntXAxis + YAxis*@CntYAxis + ZAxis*@CntZAxis)
from Test
where (latitude between @CenterLat - @SearchDistance/111.0 and @CenterLat + @SearchDistance/111.0) and
(longitude between @CenterLon - @SearchDistance/111.0 and (@CenterLon + @SearchDistance/111.0))
) Test2
And, this gives the image attached.
Now, from the outer most result, represented here by test2, if I add a condition such as you mentioned, it doesn't return anything.
The first concern I have, is as expressed earlier on, about this enormous calculated distance I obtain. This is shown in the image attached. Are those the proper values? Or, did I do something wrong in that specific calculation, referenced here by:
calculatedDistance = @EarthRadius * acos( XAxis*@CntXAxis + YAxis*@CntYAxis + ZAxis*@CntZAxis)
In the SQL.