Tuesday, June 3, 2008

Zip Code Distance in PHP or Nearest Zip Codes

Few of the times we need to select nearest of any zip code. Here is a simple script to accomplish this search easily. Moreover, only one dependence file needed what you get from

http://www.shopno-dinga.com/WebService/zipinfo/zipcodes_2006.txt

and here is php script:

Output display nearest ZIP code first

$zipMain=40011;
$zipOthers=array("15634", "22987", "31044", "40434", "50862", "81224");
foreach($zipOthers as $CurZip)
{
if($CurZip!="")
{
$handle = fopen("zipcodes_2006.txt", "rb");
$contents = '';
while (!feof($handle))
{
$contents=fread($handle, 8192)."<br>";
if(strpos($contents,"\n".$CurZip."||")>0)
{
$contents=substr($contents,strpos($contents,$CurZip),200);
$contents=explode("||",$contents);
$Lat=$contents[1];
$Lon=$contents[2];
$Distance[$CurZip]=precisionDistance($Lat, $Lon, $CurZip);
}
}
fclose($handle);
}
}
asort($Distance);
print_r($Distance); //Display Nearest ZIP code First

function precisionDistance($lat, $lon, $zip = NULL, $precision = 2)
{
$earthsradius = 3963.19;
$pi = pi();
$c = sin($starting_lat/(180/$pi)) * sin($lat/(180/$pi)) +
cos($starting_lat/(180/$pi)) * cos($lat/(180/$pi)) *
cos($lon/(180/$pi) - $starting_lon/(180/$pi));

$distance = $earthsradius * acos($c);
return round($distance,$precision);
}
?>

No comments: