Skip to main content

Get the distance between two postal codes with Google Maps

You can use Google Maps API to get a JSON string with the distance, including driving directions, between two postal codes. The code is below:

  1.   // The google maps endpoint.
  2.   $endpoint = '<a href="http://maps.google.com/maps/api/directions/json?';<br />
  3. &#10">http://maps.google.com/maps/api/directions/json?';<br />
  4. &#10</a>;  // The paramaters we need to pass to Google Maps.
  5.   $params = array(
  6.     'origin' => ORIGIN_POSTAL_CODE,
  7.     'destination' => DESTINATION_POSTAL_CODE,
  8.     'mode' => 'driving',
  9.     'sensor' => 'false',
  10.   );
  11.  
  12.   // Fetch and decode JSON string into a PHP object
  13.   $json = file_get_contents($endpoint . http_build_query($params));
  14.  
  15.   $data = json_decode($json);
  16.  
  17.   if ($data->status === 'OK') {
  18.     // Retrieve the first available route.
  19.     $route = $data->routes[0];
  20.     // Get the distance.
  21.     $distance = $route->legs[0]->distance->text;
  22.     // Break the distance into value/unit variables
  23.     list($miles, $unit) = explode(' ', $distance);
  24.     // Remove any commas.
  25.     $miles = str_replace(',', '', $miles);
  26.  
  27.     // Cast the value as a floating point number to do any comparisons.
  28.     if ((float)$miles > 2250) {
  29.       print 'TRUE';
  30.     }
  31.   }

Be sure to replace ORIGIN_POSTAL_CODE and DESTINATION_POSTAL_CODE with your respective values.

Thanks to this article for reference.


Comments