I’ve been playing around with some web services, trying to gather ZIP code data, but quickly realized that it would take forever to gather up all of the US ZIP codes—there are just under 80,000 of them. So I bit the bullet and bought a ZIP code database.
With that, I created a simple ZIP code look-up tool, which displays the city, state, latitude, longitude, etc. for any given ZIP code.
I got even more nerdy, and added a distance calculator tool that gives you distance between two ZIP codes. It’s using the haversine formula, which gives the great-circle distances between two latitude/longitude point.
Here’s are the PHP functions that I use to do the calculation:
function haversine($lat1, $long1, $lat2, $long2, $earth){
//Point 1 cords
$lat1 = deg2rad($lat1);
$long1= deg2rad($long1);
//Point 2 cords
$lat2 = deg2rad($lat2);
$long2= deg2rad($long2);
//Haversine Formula
$dlong=$long2-$long1;
$dlat=$lat2-$lat1;
$sinlat=sin($dlat/2);
$sinlong=sin($dlong/2);
$a=($sinlat*$sinlat)+cos($lat1)*cos($lat2)*($sinlong*$sinlong);
$c=2*asin(min(1,sqrt($a)));
$d=round($earth*$c);
return $d;
}
function getMiles($lat1, $long1, $lat2, $long2){
return haversine($lat1, $long1, $lat2, $long2, 3960);
}
function getKilometers($lat1, $long1, $lat2, $long2){
return haversine($lat1, $long1, $lat2, $long2, 6371);
}