Integrate the Google Maps API Into Your Website

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:

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:

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.

Destinations: Destination address(es).

Mode: Could be one of driving, walking, bicycling, or transit (API key required for transit)

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

{

"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:

1

$jsonResponse=json_decode($googleResponse);

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

1

$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:

1

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

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

1

$floatDistance=floatval($stringDistance);

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

1

returnnumber_format($floatDistance,1);

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