Question

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
Was it helpful?

Solution

The radius is in miles, therefore the returned distance is in miles. The issue you might be having is that you see a difference between the returned distance 302 and the distance returned from google maps 370. This is due to the fact that the distance returned by your function returned an exact point to point distance... as if a plane was flown from one point to the other. Driving directions include turns so the distance will be greater than the straight distance. I find that multiplying the straight distance by 1.25 usually returns and accurate result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top