Using Waypoints in Routes
As noted within the DirectionsRequest, you may also specify waypoints (of type DirectionsWaypoint) when calculating routes using the Directions service. Waypoints allow you to calculate routes through additional locations, in which case the returned route passes through the given waypoints.
A waypoint consists of the following fields:
location (required) specifies the address of the waypoint.
stopover (optional) indicates whether this waypoint is a actual stop on the route (true) or instead only a preference to route through the indicated location (false). Stopovers are true by default.
By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass
optimizeWaypoints: true within the
DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order. (This optimization is an application of the
Travelling Salesman Problem.) All waypoints must be stopovers for the Directions service to optimize their route.
If you instruct the Directions service to optimize the order of its waypoints, their order will be returned in the
optimized_waypoints_order field within the
DirectionsResult object.
The following example calculates cross-country routes across the United States using a variety of start points, end points, and waypoints. (To select multiple waypoints, press
Ctrl-Click when selecting items within the list.) Note that we inspect the
routes.start_geocode.formatted_address and
routes.end_geocode.formatted_address to provide us with the text for each route's start and end point.
(continue reading...)