Get the distance between two postal codes with Google Maps

Profile picture for user Phil Frilling
By Phil Frilling, 5 December, 2014
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:

  // The google maps endpoint.
  $endpoint = 'http://maps.google.com/maps/api/directions/json?';

  // The paramaters we need to pass to Google Maps.
  $params = array(
    'origin' => ORIGIN_POSTAL_CODE,
    'destination' => DESTINATION_POSTAL_CODE,
    'mode' => 'driving',
    'sensor' => 'false',
  );

  // Fetch and decode JSON string into a PHP object
  $json = file_get_contents($endpoint . http_build_query($params));

  $data = json_decode($json);

  if ($data->status === 'OK') {
    // Retrieve the first available route.
    $route = $data->routes[0];
    // Get the distance.
    $distance = $route->legs[0]->distance->text;
    // Break the distance into value/unit variables
    list($miles, $unit) = explode(' ', $distance);
    // Remove any commas.
    $miles = str_replace(',', '', $miles);
    
    // Cast the value as a floating point number to do any comparisons.
    if ((float)$miles > 2250) {
      print 'TRUE';
    }
  }
Be sure to replace ORIGIN_POSTAL_CODE and DESTINATION_POSTAL_CODE with your respective values. Thanks to this article for reference.