views:

1235

answers:

2

What's the best way to get a function like the following to work:

def getNearest(zipCode, miles):

That is, given a zipcode (07024) and a radius, return all zipcodes which are within that radius?

+6  A: 

There is a project on SourceForge that could assist with this:

http://sourceforge.net/projects/zips/

It gives you a database with zip codes and their latitude / longitude, as well as coding examples of how to calculate the distance between two sets of coordinates. There is probably a better way to do it, but you could have your function retrieve the zipcode and its coordinates, and then step through each zipcode in the list and add the zipcode to a list if it falls within the number of miles specified.

Patrick Harrington
+3  A: 

If you want this to be accurate, you must start with polygon data that includes the location and shape of every zipcode. I have a database like this (used to be published by the US census, but they no longer do that) and have built similar things atop it, but not that exact request.

If you don't care about being exact (which I'm guessing you don't), you can get a table of center points of zipcodes and query points ordered by great circle distance. PostGIS provides great tools for doing this, although you may construct a query against other databases that will perform similar tasks.

An alternate approach I've used is to construct a box that encompasses the circle you want, querying with a between clause on lon/lat and then doing the great-circle in app code.

Dustin