Google-maps – Can Google Maps API calculate route along multiple locations or journey legs

google mapsgoogle-maps-api-3

I'm using the Google Maps API Web Services Directions API or the Distance Matrix API to find the travel distance and time between locations.

It seems that the API only supports calculation of the route between one origin and one destination. (In case of the Distance Matrix API, multiple combinations directly between origins and destinations are computed.)

My case is that I would like to know the route (really, just traveling time and distance) of a multiple-leg journey along a series (as in an ordered array) of locations.

So, considering four locations, A, B, C, D, I know how to compute the route between any pair, A-B, A-C, A-D, B-C and so on. I want to compute the route of A-B-C-D or A-C-D-B or A-D-B-Cand so on. I supply the route and the order of the legs, so I'm not asking to solve the Traveling Salesman Problem.

Is this possible with the Google Maps Directions API or Distance Matrix API?

Obviously, I can chain the locations myself, so ask for the routes of the individual legs in separate calls, and then add them together in the desired order: A-C + C-D + D-B becomes A-C-D-B. I'm hoping that it's possible with one call.

(I've looked for similar questions, but haven't found this exact one.)

Best Answer

Thanks to @geocodezip, the answer is to add 'waypoints' between the origin and the destination, as described in the documentation of the Directions API.

For example, the request https://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA calculates the route between Boston and Concord via Charlestown and Lexington.

And the Traveling Salesman Problem is partly being solved as well, per

By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimize:true as the first argument within the waypoints parameter to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order.