#!/usr/bin/perl ############################################################################## # By BumbleBeeWare.com 2007 # zipcode distance calculator # zipdistance.cgi # reads database and calculates distance between 2 zipcodes ############################################################################## # ############################################################################## print "Content-type: text/html\n\n"; # if direct access print form for zipcode fields if($ENV{"REQUEST_METHOD"} ne "POST") { print '

To calculate the distance between 2 zipcodes specify each zipcode.
(US zipcodes only)

Zipcode 1:
Zipcode 2:
'; exit; } # otherwise calculate the distance based on form inputs and datafile # parse incoming form data read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'}); @pairs = split(/&/,$buffer); foreach $pair (@pairs){ ($name,$value) = split(/=/,$pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $form{$name} = $value; } # open the datafile and get the latatude and logitude for each zipcode open(FILE,"./zip_latlon.txt"); @zipdata = ; close(FILE); foreach $zipdata (@zipdata){ $zipcode = ""; $longitude = ""; $latitude = ""; chomp $zipdata; ($zipcode, $longitude, $latitude) =split(/\|/,$zipdata); if ($form{'zip1'} eq "$zipcode"){ $lat1 = $latitude; $lon1 = $longitude;} if ($form{'zip2'} eq "$zipcode"){ $lat2 = $latitude; $lon2 = $longitude;} } $distance = &great_circle_distance($lon1,$lat1,$lon2,$lat2); print "The distance between $form{'zip1'} and $form{'zip2'} is: $distance miles.\n"; exit; sub great_circle_distance { local($lon1,$lat1,$lon2,$lat2) = @_; # Convert all the degrees to radians $lat_1 = °_to_rad($lat1); $lon_1 = °_to_rad($lon1); $lat_2 = °_to_rad($lat2); $lon_2 = °_to_rad($lon2); # Find the deltas $delta_lat = $lat_2 - $lat_1; $delta_lon = $lon_2 - $lon_1; # Find the Great Circle distance $temp = sin($delta_lat/2.0)**2 + cos($lat_1) * cos($lat_2) * sin($delta_lon/2.0)**2; # EARTH_RADIUS = 3956 $distance = 3956 * 2 * atan2(sqrt($temp),sqrt(1-$temp)); return($distance); } # convert degrees to radians sub deg_to_rad { local($deg_2) = @_; $radians = 0.0; $pi = atan2(1,1) * 4; $radians = $deg_2 * $pi/180.0; return($radians); }