Calculating Zip Code Distances in PHP

I was recently tasked with a project that requires searching through business listings geographically. That is, being able to find all businesses within X miles of a Zip Code. At first glance, this might appear to be a simple task. On the contrary, it requires some decent math skills, a list of every postal code in the country, and corresponding latitude/longitude coordinates for each one.

Since I wasn't prepared to look up and manually enter over 42,000 postal codes, I turned to the web. Fortunately, Micah Carrick published all of this data, along with an excellent PHP Class to handle distance calculations.

The class is so well written that, once you get the postal codes in the database, the entire task of calculating all postal codes within X miles can be summed up in two lines:

$z = new zipcode_class;
$zips = $z->get_zips_in_range('97214', 2, _ZIPS_SORT_BY_DISTANCE_ASC, true);

Incredible work, Micah. Thanks for sharing this under the GNU GPL for everyone to use.

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.