Google Maps API Tutorials (JavaScript)

Google Maps API Distance Matrix Explained

Last modified on April 17th, 2023
Raja Tamil
Google Maps API Javascript

src=”” title=”YouTube video player” frameborder=”0″ allow=”accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture” allowfullscreen=””>

Distance Matrix API calculates travel distance and duration (time) between two or more locations based on transportation modes such as driving, walking, bicycling and transit.

Distance Matrix Base URL:

Distance Matrix Required Request Params

It takes one required route and FOUR query parameters.

Required Route Parameter

JSON or XMLOutput format (json recommended)

Required Query Parameters

originsThe value of this parameter will be single or multiple addresses separated by a pipe sign.

This will be the starting point for calculating the travel distance and duration.

It’ll be one of the following formats: plain street address, geographic coordinates (latitude and longitude separated by a comma) or place_id.

For Example:
origins=123+abc+Street+ON|24+Sus+Drive+Ottawa+ON origins=41.43206,-81.38992|-33.86748,151.20699
destinationsSimilar to origins, multiple locations can be added to the destinations parameter separated by a pipe sign.

This will be the ending point for calculating distance and duration. Again this can be one of the three formats.
keyYour API Key from the Google Cloud Console.
ModeThe transportation mode determines the length of the travel distance and duration. The value of this will be one of these options: driving, walking, bicycling and transit.

This is optional in the sense that if you do not specify it in the URL, the default mode will be set to driving.

Distance Matrix Response Object      

Once the request is complete and everything goes well, you’ll get an output object in JSON format like this.

As you can see, there are three arrays in the output object which are the destination addresses, origin addresses and rows.

The origin and destination address arrays will have all the addresses that we pass into the origins and destinations parameters.

The first index in the rows array will have the calculated distance and duration data.