Integrate the Google Maps API Into Your Website

By | October 22, 2016

Are you building an application that needs to calculate the cycling, walking or driving distance between two addresses? Google offers a handy service called the Google Maps Distance Matrix API that you can use to get this information and present it to your users.

The service is free, and you can specify the mode of transportation and have the distance returned in either miles or kilometers. In this post, you will learn how to write a PHP function that accepts two addresses and returns the distance between them.

Let’s take a look at the entire function and then break it down into smaller chunks:

<?php

function getDistance($addressFrom, $addressTo, $mode, $unit) {

    // Replace spaces with plus signs for the request
    $formattedAddrFrom = str_replace(' ','+',$addressFrom);
    $formattedAddrTo = str_replace(' ','+',$addressTo);

    // Send the addresses to the Google Maps Distance Matrix API
    $googleResponse = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins='.$formattedAddrFrom.'&destinations='.$formattedAddrTo.'&mode='.$mode.'&units='.$unit);
    $jsonResponse = json_decode($googleResponse);
    $stringDistance = $jsonResponse->rows[0]->elements[0]->distance->text;
    $stringDistance = str_replace(',', '', $stringDistance);
    $floatDistance = floatval($stringDistance);

    return number_format($floatDistance, 1);

}

print getDistance("Vancouver BC", "San Francisco", "driving", "imperial");

?>

First, we create a function called getDistance() that will take the origin address, destination address, mode of transportation, and desired unit of measurement.

Next, we format the addresses properly before inserting them into the request. Spaces are not allowed in URLs, so we use the function str_replace() to substitute them with plus ‘+’ characters.

Now we construct the URL with the parameters that we will pass to Google.

https://maps.googleapis.com/maps/api/distancematrix/json?origins='.$formattedAddrFrom.'&destinations='.$formattedAddrTo.'&mode=driving&units=imperial'

The URL starts with the API’s address (https://maps.googleapis.com/maps/api/distancematrix/). We specify JSON encoding (json?) and then pass it four parameters:

  1. Origins: Origin address(es). Google can return results for multiple addresses. Multiple addresses should be separated with the pipe ‘|’ symbol. In this example, we are just using a single origin and destination.
  2. Destinations: Destination address(es).
  3. Mode: Could be one of driving, walking, bicycling, or transit (API key required for transit)
  4. Units: Can be metric (kilometers) or imperial (miles)

Here’s an example of a request for the driving distance (in miles) between Vancouver, BC and San Francisco:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco&mode=driving&units=imperial

We pass the URL to the file_get_contents() function, which issues the request and returns a JSON encoded response. Here’s the JSON response for the driving distance between Vancouver, BC and San Francisco:

{
   "destination_addresses" : [ "San Francisco, CA, USA" ],
   "origin_addresses" : [ "Vancouver, BC, Canada" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "950 mi",
                  "value" : 1528365
               },
               "duration" : {
                  "text" : "14 hours 46 mins",
                  "value" : 53171
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

We decode the JSON string returned by Google with the json_decode() function:

$jsonResponse = json_decode($googleResponse);

We want to get the text value of “distance”:

$stringDistance = $jsonResponse->rows[0]->elements[0]->distance->text;

If the result is greater than 3 digits, Google will add a comma to the result. Let’s strip any commas out so that they don’t mess with our calculations:

$stringDistance = str_replace(',', '', $stringDistance);

Now we convert the numerical string to a float value using the floatval() function:

$floatDistance = floatval($stringDistance);

Finally, we use the number_format() function to return the distance to one decimal point of precision:

return number_format($floatDistance, 1);

Now we can print the distance between two addresses by calling our function:

print getDistance("Vancouver BC", "San Francisco", "driving", "imperial");

References

Google Maps Distance Matrix API

Leave a Reply

Your email address will not be published. Required fields are marked *

*