search

Simple Zip Code Perimeter Search in Rails

I recently finished up a feature that required a search to find all zip codes within a specified number of miles. I've worked with geo-coding before, but fortunately I was able to leave all the hard math to an already existing API (Google Maps, Yahoo Maps, etc.). However, for this project, we couldn't use an existing API and, fortunately, I found the math to be pretty simple.

There were several ways to approach this problem, all of them with varying degrees of complexity. The more complex the algorithm, the more accurate the search would be, but accuracy is also a trade-off for performance. I settled for the easiest and quickest route possible which is a simple box search.

Basically, with the box search, you take the geocode of your search zip code as the center point, convert the radius of your search into degrees latitude and longitude and then add/subtract degrees latitude and longitude to find the four corners of the container box. Once you have the four corners of the box represented in geocodes you can perform a simple search against your table of zip codes with their related geo codes to come up with a fairly accurate result set. (See example below)

There are 2 obvious problems with this search, one of which can be circumvented fairly easily in rails.

Syndicate content