So I have a table with a bunch of different addresses in it. I need a proc that will select the addresses in that table that are within a specified distance in miles from th
I actually wrote a short blog post a while back for exactly this purpose. Basically, the query I have is:
SELECT
Name,
Address,
City,
State,
Latitude,
Longitude,
(
ACOS(
COS(@center_latitude * (PI()/180)) *
COS(@center_longitude * (PI()/180)) *
COS(Latitude * (PI()/180)) *
COS(Longitude * (PI()/180)) +
COS(@center_latitude * (PI()/180)) *
SIN(@center_longitude * (PI()/180)) *
COS(Latitude * (PI()/180)) *
SIN(Longitude * (PI()/180)) +
SIN(@center_latitude * (PI()/180)) *
SIN(Latitude * (PI()/180))
) *
(
(@equatorial_radius * @polar_radius) /
(
SQRT(
(@equatorial_radius * @equatorial_radius) -
(
(
(@equatorial_radius * @equatorial_radius) -
(@polar_radius * @polar_radius)
) *
(
COS(@center_latitude) *
COS(@center_latitude)
)
)
)
)
)
) AS Miles
FROM
Places
WHERE
Miles <= @search_radius
Give it the center latitude, the center longitude, and the search radius and you should be good. (The parameters for the equatorial and polar radii of the Earth can be hard-coded, naturally.)
All that math is supposed to account for the curvature of the earth, the bulging at the equator, etc.
you can just use the function directly in the SP... I was thinking:
CREATE PROCEDURE [FindPlaces](@lat float, @long float, @min_dist float) AS select messageId from yourtable where dbo.F_GREAT_CIRCLE_DISTANCE(@lat, @long, lat, long)
SQL Server 2008
Using the spacial function STDistance
return distance in meters
geography::Point(@lat1, @lon1, 4326).STDistance(geography::Point(@lat2, @lon2, 4326))