A tutorial for getting travel time/distance matrices using G-maps API
Following steps are a repeat from the Tutorial for Place Search.
How to get an API key
:
- Visit https://developers.google.com/console and log in with a Google Account.
- Select one of your existing projects, or create a new project.
- Enable the API(s) you want to use. The Python Client for Google Maps Services accesses the following APIs (those in bold are to be used in the examples):
- Directions API
- Distance Matrix API
- Elevation API
- Geocoding API
- Geolocation API
- Places API
- Roads API
- Time Zone API
- Create a new Server key.
You only need one API key, but remember to enable all the APIs you need.
Direction API
By this API you can request direction information between any two places via mode=driving
, walking
, transit
or bicycling
. I managed to get query results for trips between Kyoto attraction areas via transit (accessed April 2019), in which I got the travel time, modal split (detailed bus, train route or walking), as well as the fare(if available) of the leg(s)1. However, getting transit information such as time, transfer or fare does not work well in Japan, which has been a FAQ:
Transit directions are not currently available for Japan in the Directions and Distance Matrix API. For more, see:
Nevertheless, getting results in mode=driving
or walking
seems fine. You can use coordinates formatted in a key-value dict or simply the name of places for input. Now you can see the example code.
Several comments though:
- The API accepts input in a format of coordinates or text. You may also get a detailed address of a place from a fuzzy search using Geocoding API, e.g get the detailed address of “京大 桂”. The steps are introduced in the code.
- You are strongly encouraged to look into the Python variables that represent the query results as well as the trip legs results and understand their structures. Basically they are comprised by a combination of “list”(s) and “dict”(s).
Distance matrix API
The Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations, based on the recommended route between start and end points. Compared to querying results for each single OD pair via the Direction API introduced above, this API takes an array of origins and another array of destinations as input, and returns the travel time and cost matrix. Worked fine with driving trips, but not working well for mode_choice == "transit"
(accessed in early 2019).
This is more convenient when requesting between small number of ODs, but you have to make a pause of 10 secs each time the number of queries goes beyond 100. A simple implementation of such pause is illustrated in the code.
A section or portion of a journey or course, e.g. first leg by bus, transfer to train in the second leg and then walking in the third leg. ↩︎