Directions
You can calculate directions (using a variety of methods of transportation) by using the DirectionsService object. This object communicates with the Google Maps API Directions Service which receives direction requests and returns computed results. You may either handle these directions results yourself or use the DirectionsRenderer object to render these results.
Directions may specify origins and destinations either as text strings (e.g. "Chicago, IL" or "Darwin, NSW, Australia") or as LatLng values. The Directions service can return multi-part directions using a series of waypoints. Directions are displayed as a polyline drawing the route on a map, or additionally as a series of textual description within a <div> element (e.g. "Turn right onto the Williamsburg Bridge ramp").
Directions Requests
Accessing the Directions service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method should process the result(s). Note that the Directions service may return more than one possible itinerary as an array of separate routes[].
To use directions in V3, create an object of type DirectionsService and call DirectionsService.route() to initiate a request to the Directions service, passing it a DirectionsRequest object literal containing the input terms and a callback method to execute upon receipt of the response.
The DirectionsRequest object literal contains the following fields:
{
origin: LatLng | String,
destination: LatLng | String,
travelMode: TravelMode,
unitSystem: UnitSystem,
waypoints[]: DirectionsWaypoint,
optimizeWaypoints: Boolean,
provideRouteAlternatives: Boolean,
avoidHighways: Boolean,
avoidTolls: Boolean
region: String
}These fields are explained below:
- origin (required) specifies the start location from which to calculate directions. This value may either be specified as a String (e.g. "Chicago, IL") or as a LatLng value.
- destination (required) specifies the end location to which to calculate directions. This value may either be specified as a String (e.g. "Chicago, IL") or as a LatLng value.
- travelMode (required) specifies what mode of transport to use when calculating directions. Valid values are specified in Travel Modes below.
- unitSystem (optional) specifies what unit system to use when displaying results. Valid values are specified in Unit Systems below.
- waypoints[] (optional) specifies an array of DirectionsWaypoints. Waypoints alter a route by routing it through the specified location(s). A waypoint is specified as an object literal with fields shown below:
- location specifies the location of the waypoint, either as a LatLng or as a String which will be geocoded.
- stopover is a boolean which indicates that the waypoint is a stop on the route, which has the effect of splitting the route into two routes.
- (For more information on waypoints, see Using Waypoints in Routes below.)
- optimizeWaypoints (optional) specifies that the route using the supplied waypoints may be optimized to provide the shortest possible route. If true, the Directions service will return the reordered waypoints in an waypoint_order field.(For more information, see Using Waypoints in Routes below.)
- provideRouteAlternatives (optional) when set to true specifies that the Directions service may provide more than one route alternative in the response. Note: providing route alternatives may increase the response time from the server.
- avoidHighways (optional) when set to true indicates that the calculated route(s) should avoid major highways, if possible.
- avoidTolls (optional) when set to true indicates that the calculated route(s) should avoid toll roads, if possible.
- region (optional) specifies the region code, specified as a ccTLD ("top-level domain") two-character value. (For more information see Region Biasing below.)
A sample DirectionsRequest is shown below:
{
origin: "Chicago, IL",
destination: "Los Angeles, CA",
waypoints: [
{
location:"Joplin, MO",
stopover:false
},{
location:"Oklahoma City, OK",
stopover:true
}],
provideRouteAlternatives: false,
travelMode: TravelMode.DRIVING,
unitSystem: UnitSystem.IMPERIAL
}Travel Modes
When you calculate directions, you need to specify which transportation mode to use. The following travel modes are currently supported:
- TravelMode.DRIVING indicates standard driving directions using the road network.
- TravelMode.WALKING requests walking directions via pedestrian paths & sidewalks (where available).
- New! TravelMode.BICYCLING requests bicycling directions via bicycle paths & preferred streets (currently only available in the US).
Note: Walking directions may sometimes not include clear pedestrian paths, so walking directions will return warnings in the DirectionsResult which you must display if you are not using the default DirectionsRenderer.
Unit Systems
By default, directions are calculated and displayed using the unit system of the origin's country or region. (Note: origins expressed using latitude/longitude coordinates rather than addresses always default to metric units.) For example, a route from "Chicago, IL" to "Toronto, ONT" will display results in miles, while the reverse route will display results in kilometers. You may override this unit system by setting one explicitly within the request using one of the following UnitSystem values:
- UnitSystem.METRIC specifies usage of the metric system. Distances are shown using kilometers.
- UnitSystem.IMPERIAL specifies usage of the Imperial (English) system. Distances are shown using miles.
Note: this unit system setting only affects the text displayed to the user. The directions result also contains distance values, not shown to the user, which are always expressed in meters.
Region Biasing for Directions
The Google Maps API Directions Service returns address results influenced by the domain (region or country) from which you loaded the JavaScript bootstrap. (Since most users load http://maps.google.com/ this sets an implicit domain to the United States.) If you load the bootstrap from a different supported domain, you will get results influenced by that domain. For example, searches for "San Francisco" may return different results from applications loading http://maps.google.com/ (the United States) than one loading http://maps.google.es/ (Spain).
You can also set the Directions service to return results biased to a particular region using the region parameter. This parameter takes a region code, specified as a IANA language region subtag. In most cases, these tags map directly to ccTLD ("top-level domain") two-character values such as "uk" in "co.uk" for example. In some cases, the region tag also supports ISO-3166-1 codes, which sometimes differ from ccTLD values ("GB" for "Great Britain" for example).
Consult the Google Maps coverage spreadsheet to determine to what extent a country supports directions.
Rendering Directions
Initiating a directions request to the DirectionsService with the route() method requires passing a callback which executes upon completion of the service request. This callback will return a DirectionsResult and a DirectionsStatus code in the response.
Status of Directions Query
The DirectionsStatus may return the following values:
- OK indicates the response contains a valid DirectionsResult.
- NOT_FOUND indicates at least one of the locations specified in the requests's origin, destination, or waypoints could not be geocoded.
- ZERO_RESULTS indicates no route could be found between the origin and destination.
- MAX_WAYPOINTS_EXCEEDED indicates that too many DirectionsWaypoints were provided in the DirectionsRequest. The maximum allowed waypoints is 8, plus the origin, and destination. Maps API Premier customers are allowed 23 waypoints, plus the origin, and destination.
- INVALID_REQUEST indicates that the provided DirectionsRequest was invalid.
- OVER_QUERY_LIMIT indicates the webpage has sent too many requests within the allowed time period.
- REQUEST_DENIED indicates the webpage is not allowed to use the directions service.
- UNKNOWN_ERROR indicates a directions request could not be processed due to a server error. The request may succeed if you try again.
You should ensure that the directions query returned valid results by checking this value before processing the result.
Displaying the DirectionsResult
The DirectionsResult contains the result of the directions query, which you may either handle yourself, or pass to a DirectionsRenderer object, which can automatically handle displaying the result on a map.
- Create a DirectionsRenderer object.
- Call setMap() on the renderer to bind it to the passed map.
- Call setDirections() on the renderer, passing it the DirectionsResult as noted above. Because the renderer is an MVCObject, it will automatically detect any changes to its properties and update the map when its associated directions have changed.
Displaying the Directions as a Series of Steps
A DirectionsRenderer not only handles display of the polyline and any associated markers, but also can handle the textual display of directions as a series of steps. To do so, simply call setPanel() on your DirectionsRenderer, passing it the <div> in which to display this information. Doing so also ensures that you display the appropriate copyright information, and any warnings which may be associated with the result.
Textual directions will be provided using the browser's preferred language setting, or the language specified when loading the API JavaScript using the language parameter. (For more information, see Localization.)
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));