I've found some code on here to mathematically find the distance between two zipcodes. I'm using the Google geocode api to get the long and lat from each zipcode. Everything works fine but I'm wondering how to convert the $distance
return into miles:
function calc_distance($zip1, $zip2)
{
$geo = new GoogleGeocode( $apiKey );
$point1 = $geo->geocode( $zip1 );
$point1 = $point1['Placemarks'][0];
echo "P1:"; print_r( $zip1 );
$point2 = $geo->geocode( $zip2 );
$point2 = $point2['Placemarks'][0];
echo "<br>P2: "; print_r( $zip2 ); echo "<br>";
var_dump($point1);
echo "<br><br>";
var_dump($point2);
echo "<br>";
$radius = 3958; // Earth's radius (miles)
$deg_per_rad = 57.29578; // Number of degrees/radian (for conversion)
$distance = ($radius * pi() * sqrt(
($point1['Latitude'] - $point2['Latitude'])
* ($point1['Latitude'] - $point2['Latitude'])
+ cos($point1['Latitude'] / $deg_per_rad) // Convert these to
* cos($point2['Latitude'] / $deg_per_rad) // radians for cos()
* ($point1['Longitude'] - $point2['Longitude'])
* ($point1['Longitude'] - $point2['Longitude'])
) / 180);
echo $distance;
return $distance; // Returned using the units used for $radius.
}
When I test using: calc_distance(28025, 22044);
it returns:
P1:28025
P2: 22044
array(7) { ["Accuracy"]=> int(5) ["Country"]=> string(2) "US" ["AdministrativeArea"]=> string(2) "NC" ["Locality"]=> string(7) "Concord" ["PostalCode"]=> int(28025) ["Latitude"]=> float(35.3898417) ["Longitude"]=> float(-80.5216184) }
array(7) { ["Accuracy"]=> int(5) ["Country"]=> string(2) "US" ["AdministrativeArea"]=> string(2) "VA" ["Locality"]=> string(12) "Falls Church" ["PostalCode"]=> int(22044) ["Latitude"]=> float(38.8607388) ["Longitude"]=> float(-77.1571443) }
302.952750233