XOXCO makes community sites and web apps.
This was originally posted on our blog 4 years ago by Ben Brown.
★ Zip Code Proximity Bounding Box Function
This afternoon, I am working on a project that involves zip code proximity. To find zip codes that are near to other zip codes, you need to create a geographic bounding box to search within. Creating this bounding box (really, just drawing a virtual square around your point and finding it's corners) involves a bunch of semi-scary trigonometry the likes of which I have not seen since college. I searched the internet far and wide for a pre-existing function that does this, but most of the examples I found were wrong and/or confusing. So, like the good little hacker I am, I created my own.
// find zipcodes within 100 miles of 78704
$lat = 30.240685;
$long = -97.768829;
list($lat1,$lat2,$lon1,$lon2) = getBoundingBox($lat,$long,100);
// now we can query our database and do easy number comparisons...
// ...instead of scary math!
$sql = "SELECT * FROM zipcodes WHERE latitude between $lat1 and $lat2 AND longitude between $lon1 and $lon2";
It should be noted that due to the curvature of the planet and vagaries of floating point arithmetic that this may not be 100% accurate. I encourage you to do what I'm doing - post process the results and do real distance calculations on each one to verify and refine the selection.
This code was made possible by the formulas on this handy page, and my math savvy pal Robert Swirsky.
- Ben Brown, Apr 28, 2009