What is the Distance Matrix?
A Distance Matrix is a service that provides travel distance and information between two points based on the recommended route from Google’s APIs. In the case of Google, you can also specify the mode of transportation such as walking, cycling, transit, and driving.
How does Distance Matrix work?
Google’s Distance Matrix accepts an outputFormat
and parameters
allowing you to specify a JSON output for example.
The parameters
will allow you to call the API an return the data you are looking for such as the distance between your origins
and destinations
.
Why would I want to use the Distance Matrix?
A distance matrix is a very handy tool for displaying estimated times of delivery, the travel distance between two points, and finding the closest store to your location.
How do I use the Distance Matrix then?
Login to your Google Cloud Account
Then Enable the API by heading to the API’s Library. Next, search for and enable Distance Matrix.
NOTE: There could be a cost associated with this, Make sure to read and understand your Google cloud account and how their billing works.
https://maps.googleapis.com/maps/api/distancematrix/json?mode=driving&origins=Vancouver+BC|Edmonton+AB&destinations=Victoria+BC|Calgary+AB&mode=bicycling&sensor=false&key={{key}}
What’s all this?
You can see that we passed two destination_addresses
and two origin_addresses
. The results come back in the form of elements
in the rows
array.
The order of elements is determined by the order of your origins. In this case, the first element belongs to Vancouver, the next to Edmonton.
The first result will be Vancouver to Victoria, and Vancouver to Calgary. Next would be Edmonton to Calgary, and then Edmonton to Victoria.
The values under distance
are in my case Meters, while the value under duration
is the number of minutes. The unit system can also be adjusted if needed.
Depending on your destinations you may also see fare
which will contain a currency
property.
{
"destination_addresses" : [ "Victoria, BC, Canada", "Calgary, AB, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada", "Edmonton, AB, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "114 km",
"value" : 114210
},
"duration" : {
"text" : "3 hours 2 mins",
"value" : 10893
},
"status" : "OK"
},
{
"distance" : {
"text" : "971 km",
"value" : 971039
},
"duration" : {
"text" : "10 hours 42 mins",
"value" : 38514
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "1,248 km",
"value" : 1248191
},
"duration" : {
"text" : "14 hours 49 mins",
"value" : 53315
},
"status" : "OK"
},
{
"distance" : {
"text" : "300 km",
"value" : 299642
},
"duration" : {
"text" : "3 hours 2 mins",
"value" : 10939
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
For more on Google’s Geolocation services check out their guide.
If you don’t happen to have an API key then this guide should get you on your way.