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:

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.

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:

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:

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

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

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:

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

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

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

References

Google Maps Distance Matrix API

Leave a Reply

Your email address will not be published.

*