Calculating Zip Code Distances in PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

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:

<?php
$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.

If you enjoyed this article, please share it with a friend!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>