Given coordinates, how do I get all the Zip Codes within a 10 mile radius?

AngryHacker picture AngryHacker · Nov 16, 2010 · Viewed 8.7k times · Source

I have a location (latitude & longitude). How can I get a list of zipcodes that are either partially or fully within the 10 mile radius of my location?

The solution could be a call to a well known web service (google maps, bing maps, etc...) or a local database solution (the client has sql server 2005) or an algorithm.

I have seen the somewhat similar question, but all the answers there pretty much pertain to using SQL Server 2008 geography functionality which is unavailable to me.

Answer

dana picture dana · Nov 18, 2010

Start with a zip code database that contains zipcodes and their corresponding latitude and longitude coordinates:

http://www.zipcodedownload.com/Products/Product/Z5Commercial/Standard/Overview/

To get the distance between latitude and longitude, you will need a good distance formula. This site has a couple variations:

http://www.meridianworlddata.com/distance-calculation/

The "Great Circle Distance" formula is a little extreme. This one works well enough from my experience:

sqrt(x * x + y * y)

where x = 69.1 * (lat2 - lat1)
and y = 69.1 * (lon2 - lon1) * cos(lat1/57.3)

Your SQL Query will then look something like this:

select zd.ZipCode
from ZipData zd
where 
    sqrt(
        square(69.1 * (zd.Latitude - @Latitude)) +
        square(69.1 * (zd.Longitude - @Longitude) * cos(@Latitude/57.3))
    ) < @Distance

Good luck!