This service is also available as part of the client-side Maps JavaScript API, or for server-side use with the Java Client, Python Client, Go Client and Node.js Client for Google Maps Services.
Introduction
The Directions API is a service that calculates directions between locations using an HTTP request.
This video illustrates the use of the Directions API to help people find their way. The video includes advice on proxying the web service via your server when you're using the API in a mobile app, to protect your API key.
With the Directions API, you can:
- Search for directions for several modes of transportation, including transit, driving, walking or cycling.
- Return multi-part directions using a series of waypoints.
- Specify origins, destinations, and waypoints as text strings (e.g. "Chicago, IL" or "Darwin, NT, Australia"), or as latitude/longitude coordinates, or as place IDs.
The API returns the most efficient routes when calculating directions. Travel time is the primary factor optimized, but the API may also take into account other factors such as distance, number of turns and many more when deciding which route is the most efficient.
Note: This service is not designed to respond in real time to user input. For dynamic directions calculations (for example, within a user interface element), consult the documentation for the Maps JavaScript API Directions Service.
Before you begin
This document is intended for website and mobile developers who want to compute direction data within maps provided by one of the Google Maps APIs. It provides an introduction to using the API and reference material on the available parameters.
Before you start developing with the Directions API, review the authentication requirements (you need an API key) and the API usage and billing information (you need to enable billing on your project).
Directions Requests
A Directions API request takes the following form:
https://maps.googleapis.com/maps/api/directions/outputFormat?parameters
where outputFormat
may be either of the following values:
json
(recommended) indicates output in JavaScript Object Notation (JSON)xml
indicates output as XML
Note: URLs must be properly encoded to be valid and are limited to 8192 characters for all web services. Be aware of this limit when constructing your URLs.
HTTPS or HTTP
Security is important and HTTPS is recommended whenever possible, especially for applications that include sensitive user data, such as a user's location, in requests. Using HTTPS encryption makes your application more secure, and more resistant to snooping or tampering.
If HTTPS is not possible, to access the Directions API over HTTP, use:
http://maps.googleapis.com/maps/api/directions/outputFormat?parameters
Request Parameters
Certain parameters are required while others are optional. As is
standard in URLs, all parameters are separated using the ampersand
(&
) character. The list of parameters and their possible
values are enumerated below.
Required parameters
origin
— The address, textual latitude/longitude value, or place ID from which you wish to calculate directions.- If you pass an address, the Directions service
geocodes the string and converts it to a latitude/longitude coordinate to
calculate directions. This coordinate may be different from that
returned by the Geocoding API, for example a building
entrance rather than its center.
origin=24+Sussex+Drive+Ottawa+ON
- If you pass coordinates, they are used unchanged to calculate
directions. Ensure that no space exists between the latitude and
longitude values.
origin=41.43206,-81.38992
- Place IDs must be prefixed with
place_id:
. The place ID may only be specified if the request includes an API key or a Google Maps Platform Premium Plan client ID. You can retrieve place IDs from the Geocoding API and the Places API (including Place Autocomplete). For an example using place IDs from Place Autocomplete, see Place Autocomplete and Directions. For more about place IDs, see the Place ID overview.origin=place_id:ChIJ3S-JXmauEmsRUcIaWtf4MzE
- If you pass an address, the Directions service
geocodes the string and converts it to a latitude/longitude coordinate to
calculate directions. This coordinate may be different from that
returned by the Geocoding API, for example a building
entrance rather than its center.
destination
— The address, textual latitude/longitude value, or place ID to which you wish to calculate directions. The options for thedestination
parameter are the same as for theorigin
parameter, described above.key
— Your application's API key. This key identifies your application for purposes of quota management. Learn how to get a key.Note: Google Maps Platform Premium Plan customers may use either an API key, or a valid client ID and digital signature, in your Directions requests. Get more information on authentication parameters for Premium Plan customers.
Optional parameters
mode
(defaults todriving
) — Specifies the mode of transport to use when calculating directions. Valid values and other request details are specified in Travel Modes.waypoints
— Specifies an array of intermediate locations to include along the route between the origin and destination points as pass through or stopover locations. Waypoints alter a route by directing it through the specified location(s). The API supports waypoints for these travel modes: driving, walking and bicycling; not transit. You can specify waypoints using the following values:- Latitude/longitude coordinates (
lat/lng
): an explicit value pair. (-34.92788%2C138.60008
comma, no space) - Place ID: The unique value specific to a location. This value is only available only if the
request includes an API key or Google Maps Platform Premium Plan client ID
(
ChIJGwVKWe5w44kRcr4b9E25-Go
. - Address string (
Charlestown, Boston,MA
) - Encoded polyline that can be specified by a set of any of the above.
(
enc:lexeF{~wsZejrPjtye@:
)
- Latitude/longitude coordinates (
alternatives
— If set totrue
, specifies that the Directions service may provide more than one route alternative in the response. Note that providing route alternatives may increase the response time from the server. This is only available for requests without intermediate waypoints.avoid
— Indicates that the calculated route(s) should avoid the indicated features. This parameter supports the following arguments:tolls
indicates that the calculated route should avoid toll roads/bridges.highways
indicates that the calculated route should avoid highways.ferries
indicates that the calculated route should avoid ferries.indoor
indicates that the calculated route should avoid indoor steps for walking and transit directions. Only requests that include an API key or a Google Maps Platform Premium Plan client ID will receive indoor steps by default.
language
— The language in which to return results.- See the list of supported languages. Google often updates the supported languages, so this list may not be exhaustive.
- If
language
is not supplied, the API attempts to use the preferred language as specified in theAccept-Language
header, or the native language of the domain from which the request is sent. - The API does its best to provide a street address that is readable for both the user and locals. To achieve that goal, it returns street addresses in the local language, transliterated to a script readable by the user if necessary, observing the preferred language. All other addresses are returned in the preferred language. Address components are all returned in the same language, which is chosen from the first component.
- If a name is not available in the preferred language, the API uses the closest match.
- The preferred language has a small influence on the set of results that the API chooses to return, and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, such as the abbreviations for street types, or synonyms that may be valid in one language but not in another. For example, utca and tér are synonyms for street in Hungarian.
units
— Specifies the unit system to use when displaying results. Valid values are specified in Unit Systems below.region
— Specifies the region code, specified as a ccTLD ("top-level domain") two-character value. (For more information see Region Biasing below.)arrival_time
— Specifies the desired time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. You can specify eitherdeparture_time
orarrival_time
, but not both. Note thatarrival_time
must be specified as an integer.departure_time
— Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. Alternatively, you can specify a value ofnow
, which sets the departure time to the current time (correct to the nearest second). The departure time may be specified in two cases:- For requests where the travel mode is transit: You can optionally
specify one of
departure_time
orarrival_time
. If neither time is specified, thedeparture_time
defaults to now (that is, the departure time defaults to the current time). - For requests where the travel mode is driving: You can specify the
departure_time
to receive a route and trip duration (response field:duration_in_traffic
) that take traffic conditions into account. This option is only available if the request contains a valid API key, or a valid Google Maps Platform Premium Plan client ID and signature. Thedeparture_time
must be set to the current time or some time in the future. It cannot be in the past.Note: If departure time is not specified, choice of route and duration are based on road network and average time-independent traffic conditions. Results for a given request may vary over time due to changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency.
- For requests where the travel mode is transit: You can optionally
specify one of
traffic_model
(defaults tobest_guess
) — Specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in theduration_in_traffic
field in the response, which contains the predicted time in traffic based on historical averages. Thetraffic_model
parameter may only be specified for driving directions where the request includes adeparture_time
, and only if the request includes an API key or a Google Maps Platform Premium Plan client ID. The available values for this parameter are:best_guess
(default) indicates that the returnedduration_in_traffic
should be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer thedeparture_time
is to now.pessimistic
indicates that the returnedduration_in_traffic
should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.optimistic
indicates that the returnedduration_in_traffic
should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.
best_guess
will give the most useful predictions for the vast majority of use cases. It is possible thebest_guess
travel time prediction may be shorter thanoptimistic
, or alternatively, longer thanpessimistic
, due to the way thebest_guess
prediction model integrates live traffic information.transit_mode
— Specifies one or more preferred modes of transit. This parameter may only be specified for transit directions, and only if the request includes an API key or a Google Maps Platform Premium Plan client ID. The parameter supports the following arguments:bus
indicates that the calculated route should prefer travel by bus.subway
indicates that the calculated route should prefer travel by subway.train
indicates that the calculated route should prefer travel by train.tram
indicates that the calculated route should prefer travel by tram and light rail.rail
indicates that the calculated route should prefer travel by train, tram, light rail, and subway. This is equivalent totransit_mode=train|tram|subway
.
transit_routing_preference
— Specifies preferences for transit routes. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. This parameter may only be specified for transit directions, and only if the request includes an API key or a Google Maps Platform Premium Plan client ID. The parameter supports the following arguments:less_walking
indicates that the calculated route should prefer limited amounts of walking.fewer_transfers
indicates that the calculated route should prefer a limited number of transfers.
Example Directions Requests
The following request returns driving directions from Toronto, Ontario to Montreal, Quebec.
https://maps.googleapis.com/maps/api/directions/json?
origin=Toronto&destination=Montreal
&key=YOUR_API_KEY
By changing the mode
and avoid
parameters,
the initial request can be modified to return directions for a
scenic bicycle journey that avoids major highways.
https://maps.googleapis.com/maps/api/directions/json?
origin=Toronto&destination=Montreal
&avoid=highways
&mode=bicycling
&key=YOUR_API_KEY
The following request searches for transit directions from Brooklyn, New York
to Queens, New York. The request does not specify a
departure_time
, so the departure time defaults to the current
time:
https://maps.googleapis.com/maps/api/directions/json?
origin=Brooklyn&destination=Queens
&mode=transit
&key=YOUR_API_KEY
The following transit request includes a specific departure time.
Note: In this example the departure time is specified as July 30, 2012 at 09:45 am. To avoid an error, you must change the parameter to a time in the future before submitting the request.
https://maps.googleapis.com/maps/api/directions/json?
origin=Brooklyn&destination=Queens
&departure_time=1343641500&mode=transit
&key=YOUR_API_KEY
The following request returns driving directions from Glasgow, UK to Perth, UK using place IDs.
https://maps.googleapis.com/maps/api/directions/json?
origin=place_id:ChIJ685WIFYViEgRHlHvBbiD5nE
&destination=place_id:ChIJA01I-8YVhkgRGJb0fW4UX7Y
&key=YOUR_API_KEY
Travel Modes
When you calculate directions, you may specify
the transportation mode
to use. By default,
directions are calculated as driving
directions. The following
travel modes are supported:
driving
(default) indicates standard driving directions using the road network.walking
requests walking directions via pedestrian paths & sidewalks (where available).bicycling
requests bicycling directions via bicycle paths & preferred streets (where available).transit
requests directions via public transit routes (where available). If you set the mode totransit
, you can optionally specify either adeparture_time
or anarrival_time
. If neither time is specified, thedeparture_time
defaults to now (that is, the departure time defaults to the current time). You can also optionally include atransit_mode
and/or atransit_routing_preference
.
Note: Both walking and
bicycling directions may sometimes not include clear pedestrian or
bicycling paths, so these directions will return warnings
in the returned result which you must display to the user.
Traffic Information
Traffic information is used when all of the following apply (these are the
conditions required to receive the
duration_in_traffic
field in the Directions response):
- The
travel
mode
parameter isdriving
, or is not specified (driving
is the default travel mode). - The request includes a valid
departure_time
parameter. Thedeparture_time
can be set to the current time or some time in the future. It cannot be in the past. - The request does not include stopover
waypoints. If the request
includes waypoints, prefix each waypoint with
via:
to influence the route but avoid stopovers. For example,&waypoints=via:San Francisco|via:Mountain View|...
Optionally, you can include the
traffic_model
parameter in your request to specify the assumptions to use when
calculating time in traffic.
The following URL initiates a Directions request for a journey from Boston, MA to
Concord, MA, via Charlestown and Lexington. The request includes a departure time, meeting
all the requirements to return the duration_in_traffic
field in the Directions
response.
https://maps.googleapis.com/maps/api/directions/json?
origin=Boston,MA&destination=Concord,MA
&waypoints=via:Charlestown,MA|via:Lexington,MA
&departure_time=now
&key=YOUR_API_KEY
Waypoints
When calculating routes using the Directions API, you may specify waypoints to return a route that includes pass throughs or stopovers at intermediate locations. You can add waypoints to driving, walking or bicycling directions but not transit directions.
Specify locations in the waypoints
parameter.
You can supply one or more locations separated by the pipe character
(|
or %7C
), in the form of a place ID, an address, or latitude/longitude
coordinates. By default, the Directions service calculates a route using the waypoints in the order
they are given. The precedence for parsing the value of the waypoint is place ID, latitude/longitude
coordinates, then address.
- If you pass a place ID, you must prefix it with
place_id:
and append an API key or a Google Maps Platform Premium Plan client ID. You can retrieve place IDs from the Geocoding API and the Places API (including Place Autocomplete). For an example using place IDs from Place Autocomplete, see Place Autocomplete and Directions. For more about place IDs, see the Place ID overview.For efficiency and accuracy, use place ID's when possible. These ID's are uniquely explicit like a lat/lng value pair and provide geocoding benefits for routing such as access points and traffic variables. Unlike an address, ID's do not require the service to perform a search or an intermediate request for place details; therefore, performance is better.
- If you pass latitude/longitude coordinates, the values go directly to the front-end server
to calculate directions without geocoding. The points are snapped to roads and might not provide
the accuracy your app needs. Use coordinates when you are confident the values truly specify the
points your app needs for routing without regard to possible access points or additional geocoding
details. Ensure that a comma (
%2C
) and not a space (%20
) separates the latitude and longitude values. - If you pass an address, the Directions service will geocode the string and convert it into latitude/longitude coordinates to calculate directions. If the address value is ambiguous, the value might evoke a search to disambiguate from similar addresses. For example, "1st Street" could be a complete value or a partial value for "1st street NE" or "1st St SE". This result may be different from that returned by the Geocoding API. You can avoid possible misinterpretations using place IDs. See troubleshooting the results of my route request.
Alternatively, you can supply an encoded set of points using the Encoded Polyline Algorithm. You will find an encoded set is useful for a large number of waypoints, because the URL is significantly shorter. All web services have a URL limit of 8192 characters.
- Encoded polylines must be prefixed with
enc:
and followed by a colon (:
). For example:waypoints=enc:gfo}EtohhU:
. - You can also include multiple encoded polylines, separated by the pipe
character (
|
). For example,waypoints=via:enc:wc~oAwquwMdlTxiKtqLyiK:|enc:c~vnAamswMvlTor@tjGi}L:| via:enc:udymA{~bxM:
The following URL initiates a Directions request for a journey between Boston, MA and Concord, MA with stopovers in Charlestown and Lexington, in that order. The example uses addresses:
https://maps.googleapis.com/maps/api/directions/json?
origin=Boston,MA&destination=Concord,MA
&waypoints=Charlestown,MA|Lexington,MA
&key=YOUR_API_KEY
Influence routes with stopover and pass through points
For each waypoint in the request, the directions response appends an
entry to the legs
array to provide the
details for stopovers on that leg of the journey.
If you'd like to influence the route using waypoints without adding a
stopover, add the prefix via:
to the waypoint. Waypoints
prefixed with via:
will not add an entry to the
legs
array, but will route the journey
through the waypoint.
The following URL modifies the previous request such that the journey is routed through Lexington without stopping:
https://maps.googleapis.com/maps/api/directions/json?
origin=Boston,MA&destination=Concord,MA
&waypoints=Charlestown,MA|via:Lexington,MA
&key=YOUR_API_KEY
The via:
prefix is most effective when creating routes
in response to the user dragging the waypoints on the map. Doing so allows
the user to see how the final route may look in real-time and helps ensure that
waypoints are placed in locations that are accessible to the Directions API.
The following URL requests waypoints using latitude/longitude coordinates:
https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY
Here is the same request, using an encoded polyline:
https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:enc:lexeF{~wsZejrPjtye@:
&key=YOUR_API_KEY
Optimize your waypoints
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. (This optimization is an application of the
traveling salesperson problem.) Travel time is the primary factor which is
optimized, but other factors such as distance, number of turns and many more
may be taken into account when deciding which route is the most efficient. 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
waypoint_order
field within the
routes
object.
The waypoint_order
field
returns values which are zero-based.
The following example calculates a road journey from Adelaide, South Australia to each of South Australia's main wine regions using route optimization.
https://maps.googleapis.com/maps/api/directions/json?
origin=Adelaide,SA&destination=Adelaide,SA
&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA
&key=YOUR_API_KEY
Inspection of the calculated route will indicate that calculation uses waypoints in the following waypoint order:
"waypoint_order": [ 3, 2, 0, 1 ]
Restrictions
Directions may be calculated that adhere to certain restrictions. Restrictions
are indicated by use of the avoid
parameter, and an argument to that
parameter indicating the restriction to avoid. The following restrictions are supported:
avoid=tolls
avoid=highways
avoid=ferries
It's possible to request a route that avoids any combination of tolls, highways and ferries by
passing both restrictions to the avoid parameter. For example:
avoid=tolls|highways|ferries
.
Note: the addition of restrictions does not preclude routes that include the restricted feature; it simply biases the result to more favorable routes.
Unit Systems
Directions results contain text
within distance
fields that may be displayed to the user to indicate the distance of a
particular "step" of the route. By default, this text uses the unit system
of the origin's country or region.
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's units
parameter, passing one of the following
values:
metric
specifies usage of the metric system. Textual distances are returned using kilometers and meters.imperial
specifies usage of the Imperial (English) system. Textual distances are returned using miles and feet.
Note: this unit system setting only
affects the text
displayed within distance
fields. The distance
fields also contain values
which are always expressed in meters.
Region Biasing
You can set the Directions service to return results from a
specific region by using the region
parameter. This parameter
takes a ccTLD (country code
top-level domain) argument specifying the region bias. Most ccTLD codes are
identical to ISO 3166-1 codes, with some notable exceptions. For example,
the United Kingdom's ccTLD is "uk" (.co.uk
) while its ISO 3166-1
code is "gb" (technically for the entity of "The United Kingdom of Great
Britain and Northern Ireland").
You may utilize any domain in which the main Google Maps application has launched driving directions.
For example, a directions request for "Toledo" to "Madrid"
returns appropriate results when region
is set to es
and "Toledo" is then interpreted as the Spanish city:
https://maps.googleapis.com/maps/api/directions/json?
origin=Toledo&destination=Madrid
®ion=es
&key=YOUR_API_KEY
{
"status": "OK",
"routes": [ {
"summary": "AP-41",
"legs": [ {
...
} ],
"copyrights": "Map data ©2010 Europa Technologies, Tele Atlas",
"warnings": [ ],
"waypoint_order": [ ]
} ]
}
A directions request for "Toledo" to "Madrid" sent without a region
parameter does not return results, because "Toledo" is interpreted as the
city in Ohio and not Spain:
https://maps.googleapis.com/maps/api/directions/json?
origin=Toledo&destination=Madrid
&key=YOUR_API_KEY
{
"status": "ZERO_RESULTS",
"routes": [ ]
}
Directions Responses
Directions responses are returned in the format indicated by the
output
flag within the URL request's path.
Sample Responses
A sample HTTP request is shown below, calculating the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK.
https://maps.googleapis.com/maps/api/directions/json?
origin=Chicago,IL&destination=Los+Angeles,CA
&waypoints=Joplin,MO|Oklahoma+City,OK
&key=YOUR_API_KEY
The above example requests JSON output. It's also possible to request XML output. Click the tabs below to see the sample JSON and XML responses.
Because directions results can be quite verbose, repeated elements within the responses have been omitted for clarity.
{ "status": "OK", "geocoded_waypoints" : [ { "geocoder_status" : "OK", "place_id" : "ChIJ7cv00DwsDogRAMDACa2m4K8", "types" : [ "locality", "political" ] }, { "geocoder_status" : "OK", "place_id" : "ChIJ69Pk6jdlyIcRDqM1KDY3Fpg", "types" : [ "locality", "political" ] }, { "geocoder_status" : "OK", "place_id" : "ChIJgdL4flSKrYcRnTpP0XQSojM", "types" : [ "locality", "political" ] }, { "geocoder_status" : "OK", "place_id" : "ChIJE9on3F3HwoAR9AhGJW_fL-I", "types" : [ "locality", "political" ] } ], "routes": [ { "summary": "I-40 W", "legs": [ { "steps": [ { "travel_mode": "DRIVING", "start_location": { "lat": 41.8507300, "lng": -87.6512600 }, "end_location": { "lat": 41.8525800, "lng": -87.6514100 }, "polyline": { "points": "a~l~Fjk~uOwHJy@P" }, "duration": { "value": 19, "text": "1 min" }, "html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e", "distance": { "value": 207, "text": "0.1 mi" } }, ... ... additional steps of this leg ... ... additional legs of this route "duration": { "value": 74384, "text": "20 hours 40 mins" }, "distance": { "value": 2137146, "text": "1,328 mi" }, "start_location": { "lat": 35.4675602, "lng": -97.5164276 }, "end_location": { "lat": 34.0522342, "lng": -118.2436849 }, "start_address": "Oklahoma City, OK, USA", "end_address": "Los Angeles, CA, USA" } ], "copyrights": "Map data ©2010 Google, Sanborn", "overview_polyline": { "points": "a~l~Fjk~uOnzh@vlbBtc~@tsE`vnApw{A`dw@~w\\|tNtqf@l{Yd_Fblh@rxo@b}@xxSfytA blk@xxaBeJxlcBb~t@zbh@jc|Bx}C`rv@rw|@rlhA~dVzeo@vrSnc}Axf]fjz@xfFbw~@dz{A~d{A|zOxbrBbdUvpo@` cFp~xBc`Hk@nurDznmFfwMbwz@bbl@lq~@loPpxq@bw_@v|{CbtY~jGqeMb{iF|n\\~mbDzeVh_Wr|Efc\\x`Ij{kE}mAb ~uF{cNd}xBjp]fulBiwJpgg@|kHntyArpb@bijCk_Kv~eGyqTj_|@`uV`k|DcsNdwxAott@r}q@_gc@nu`CnvHx`k@dse @j|p@zpiAp|gEicy@`omFvaErfo@igQxnlApqGze~AsyRzrjAb__@ftyB}pIlo_BflmA~yQftNboWzoAlzp@mz`@|}_ @fda@jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC" }, "warnings": [ ], "waypoint_order": [ 0, 1 ], "bounds": { "southwest": { "lat": 34.0523600, "lng": -118.2435600 }, "northeast": { "lat": 41.8781100, "lng": -87.6297900 } } } ] }
Generally, only one entry in the routes
array is returned
for directions lookups, though the Directions service may return several routes
if you pass alternatives=true
.
Note that these results generally need to be parsed if you wish to extract values from the results. Parsing JSON is relatively easy. See Parsing JSON for some recommended design patterns.
<DirectionsResponse> <status>OK</status> <geocoded_waypoint> <geocoder_status>OK</geocoder_status> <type>locality</type> <type>political</type> <place_id>ChIJ7cv00DwsDogRAMDACa2m4K8</place_id> </geocoded_waypoint> <geocoded_waypoint> <geocoder_status>OK</geocoder_status> <type>locality</type> <type>political</type> <place_id>ChIJ69Pk6jdlyIcRDqM1KDY3Fpg</place_id> </geocoded_waypoint> <geocoded_waypoint> <geocoder_status>OK</geocoder_status> <type>locality</type> <type>political</type> <place_id>ChIJgdL4flSKrYcRnTpP0XQSojM</place_id> </geocoded_waypoint> <geocoded_waypoint> <geocoder_status>OK</geocoder_status> <type>locality</type> <type>political</type> <place_id>ChIJE9on3F3HwoAR9AhGJW_fL-I</place_id> </geocoded_waypoint> <route> <summary>I-40 W</summary> <leg> <step> <travel_mode>DRIVING</travel_mode> <start_location> <lat>41.8507300</lat> <lng>-87.6512600</lng> </start_location> <end_location> <lat>41.8525800</lat> <lng>-87.6514100</lng> </end_location> <polyline> <points>a~l~Fjk~uOwHJy@P</points> </polyline> <duration> <value>19</value> <text>1 min</text> </duration> <html_instructions>Head <b>north</b> on <b>S Morgan St</b> toward <b>W Cermak Rd</b></html_instructions> <distance> <value>207</value> <text>0.1 mi</text> </distance> </step> ... ... additional steps of this leg ... ... additional legs of this route <duration> <value>74384</value> <text>20 hours 40 mins</text> </duration> <distance> <value>2137146</value> <text>1,328 mi</text> </distance> <start_location> <lat>35.4675602</lat> <lng>-97.5164276</lng> </start_location> <end_location> <lat>34.0522342</lat> <lng>-118.2436849</lng> </end_location> <start_address>Oklahoma City, OK, USA</start_address> <end_address>Los Angeles, CA, USA</end_address> <copyrights>Map data ©2010 Google, Sanborn</copyrights> <overview_polyline> <points>a~l~Fjk~uOnzh@vlbBtc~@tsE`vnApw{A`dw@~w\|tNtqf@l{Yd_Fblh@rxo@b}@xxSfytAblk@xxaBeJ xlcBb~t@zbh@jc|Bx}C`rv@rw|@rlhA~dVzeo@vrSnc}Axf]fjz@xfFbw~@dz{A~d{A|zOxbrBbdUvpo@`cFp~xBc`Hk@nur DznmFfwMbwz@bbl@lq~@loPpxq@bw_@v|{CbtY~jGqeMb{iF|n\~mbDzeVh_Wr|Efc\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiw Jpgg@|kHntyArpb@bijCk_Kv~eGyqTj_|@`uV`k|DcsNdwxAott@r}q@_gc@nu`CnvHx`k@dse@j|p@zpiAp|gEicy@`omFva Erfo@igQxnlApqGze~AsyRzrjAb__@ftyB}pIlo_BflmA~yQftNboWzoAlzp@mz`@|}_@fda@jakEitAn{fB_a]lexClshBtm qAdmY_hLxiZd~XtaBndgC</points> </overview_polyline> <waypoint_index>0</waypoint_index> <waypoint_index>1</waypoint_index> <bounds> <southwest> <lat>34.0523600</lat> <lng>-118.2435600</lng> </southwest> <northeast> <lat>41.8781100</lat> <lng>-87.6297900</lng> </northeast> </bounds> </route> </DirectionsResponse>
Note that the XML response consists of a single <DirectionsResponse>
and the following top-level elements:
<status>
contains metadata on the request. See Status Codes below.- One
<geocoded_waypoint>
per waypoint, plus origin and destination, with details about the result of geocoding these. There may be empty<geocoded_waypoint/>
elements. See Geocoded Waypoints below. - Zero or more
<route>
elements, each containing a single set of routing information between the origin and destination.
We recommend that you use json
as the preferred output flag
unless your service requires xml
for some reason. Processing XML
trees requires some care, so that you reference proper nodes and elements. See
Parsing XML
with XPath for some recommended design patterns for output processing.
The remainder of this documentation will use JSON syntax. In most cases, the output format does not matter for purposes of illustrating concepts or field names in the documentation. However, note the following subtle differences:
- XML results are wrapped in a root
<DirectionsResponse>
element. - JSON denotes entries with multiple elements by plural arrays (such as
steps
andlegs
), while XML denotes these using multiple singular elements (such as<step>
and<leg>
). - JSON denotes waypoint order via the
waypoint_order
field, while XML denotes these using individual<waypoint_index>
elements. - Blank elements are indicated through empty arrays in JSON, but by the absence of any
such element in XML. A response that generates no results will return an empty
routes
array in JSON, but no<route>
elements in XML, for example.
Directions Response Elements
Directions responses contain the following root elements:
status
contains metadata on the request. See Status Codes below.geocoded_waypoints
contains an array with details about the geocoding of origin, destination and waypoints. See Geocoded Waypoints below.routes
contains an array of routes from the origin to the destination. See Routes below. Routes consist of nested Legs and Steps.available_travel_modes
contains an array of available travel modes. This field is returned when a request specifies a travelmode
and gets no results. The array contains the available travel modes in the countries of the given set of waypoints. This field is not returned if one or more of the waypoints arevia:
waypoints. See details below.
Status Codes
The status
field within the Directions response object contains the status
of the request, and may contain debugging information to help you track down why the
Directions service failed. The status
field may contain the following
values:
OK
indicates the response contains a validresult
.NOT_FOUND
indicates at least one of the locations specified in the request'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 manywaypoints
were provided in the request. For applications using the Directions API as a web service, or the directions service in the Maps JavaScript API, the maximum allowed number ofwaypoints
is 25, plus the origin and destination.MAX_ROUTE_LENGTH_EXCEEDED
indicates the requested route is too long and cannot be processed. This error occurs when more complex directions are returned. Try reducing the number of waypoints, turns, or instructions.INVALID_REQUEST
indicates that the provided request was invalid. Common causes of this status include an invalid parameter or parameter value.OVER_DAILY_LIMIT
indicates any of the following:- The API key is missing or invalid.
- Billing has not been enabled on your account.
- A self-imposed usage cap has been exceeded.
- The provided method of payment is no longer valid (for example, a credit card has expired).
See the Maps FAQ to learn how to fix this.
OVER_QUERY_LIMIT
indicates the service has received too many requests from your application within the allowed time period.REQUEST_DENIED
indicates that the service denied use of the directions service by your application.UNKNOWN_ERROR
indicates a directions request could not be processed due to a server error. The request may succeed if you try again.
Error Messages
When the status code is other than OK
, there may be an additional
error_message
field within the Directions response object. This field contains more
detailed information about the reasons behind the given status code.
Note: This field is not guaranteed to be always present, and its content is subject to change.
Geocoded Waypoints
Details about the geocoding of every waypoint, as well as origin and destination,
can be found in the (JSON) geocoded_waypoints
array. These can be used to infer why
the service would return unexpected or no routes.
Elements in the geocoded_waypoints
array correspond, by their zero-based position,
to the origin, the waypoints in the order they are specified, and the destination. Each element
includes the following details about the geocoding operation for the corresponding waypoint:
geocoder_status
indicates the status code resulting from the geocoding operation. This field may contain the following values."OK"
indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned."ZERO_RESULTS"
indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existentaddress
.
-
partial_match
indicates that the geocoder did not return an exact match for the original request, though it was able to match part of the requested address. You may wish to examine the original request for misspellings and/or an incomplete address.Partial matches most often occur for street addresses that do not exist within the locality you pass in the request. Partial matches may also be returned when a request matches two or more locations in the same locality. For example, "21 Henr St, Bristol, UK" will return a partial match for both Henry Street and Henrietta Street. Note that if a request includes a misspelled address component, the geocoding service may suggest an alternative address. Suggestions triggered in this way will also be marked as a partial match.
place_id
is a unique identifier that can be used with other Google APIs. For example, you can use theplace_id
from a Google Place Autocomplete response to calculate directions to a local business. See the Place ID overview.types
indicates the address type of the geocoding result used for calculating directions. The following types are returned:street_address
indicates a precise street address.route
indicates a named route (such as "US 101").intersection
indicates a major intersection, usually of two major roads.political
indicates a political entity. Usually, this type indicates a polygon of some civil administration.country
indicates the national political entity, and is typically the highest order type returned by the Geocoder.administrative_area_level_1
indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels. In most cases, administrative_area_level_1 short names will closely match ISO 3166-2 subdivisions and other widely circulated lists; however this is not guaranteed as our geocoding results are based on a variety of signals and location data.administrative_area_level_2
indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.administrative_area_level_3
indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.administrative_area_level_4
indicates a fourth-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.administrative_area_level_5
indicates a fifth-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.colloquial_area
indicates a commonly-used alternative name for the entity.locality
indicates an incorporated city or town political entity.sublocality
indicates a first-order civil entity below a locality. For some locations may receive one of the additional types:sublocality_level_1
tosublocality_level_5
. Each sublocality level is a civil entity. Larger numbers indicate a smaller geographic area.neighborhood
indicates a named neighborhoodpremise
indicates a named location, usually a building or collection of buildings with a common namesubpremise
indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common namepostal_code
indicates a postal code as used to address postal mail within the country.natural_feature
indicates a prominent natural feature.airport
indicates an airport.park
indicates a named park.point_of_interest
indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category, such as "Empire State Building" or "Eiffel Tower".
These details will not be present for waypoints specified as textual latitude/longitude values
if the service returns no results. This is because such waypoints are only reverse geocoded to
obtain their representative address after a route has been found. An empty JSON object will occupy
the corresponding places in the geocoded_waypoints
array.
Routes
When the Directions API returns results, it places them
within a (JSON) routes
array. Even if the service returns
no results (such as if the origin and/or destination doesn't exist) it
still returns an empty routes
array. (XML responses consist
of zero or more <route>
elements.)
Each element of the routes
array contains a single result
from the specified origin and destination. This route may consist of
one or more legs
depending on whether any waypoints
were specified. As well, the route also contains copyright and warning
information which must be displayed to the user in addition to the
routing information.
Each route within the routes
field may contain
the following fields:
summary
contains a short textual description for the route, suitable for naming and disambiguating the route from alternatives.legs[]
contains an array which contains information about a leg of the route, between two locations within the given route. A separate leg will be present for each waypoint or destination specified. (A route with no waypoints will contain exactly one leg within thelegs
array.) Each leg consists of a series ofsteps
. (See Directions Legs below.)waypoint_order
(or<waypoint_index>
in XML) contains an array indicating the order of any waypoints in the calculated route. This waypoints may be reordered if the request was passedoptimize:true
within itswaypoints
parameter.overview_polyline
contains a singlepoints
object that holds an encoded polyline representation of the route. This polyline is an approximate (smoothed) path of the resulting directions.bounds
contains the viewport bounding box of theoverview_polyline
.copyrights
contains the copyrights text to be displayed for this route. You must handle and display this information yourself.warnings[]
contains an array of warnings to be displayed when showing these directions. You must handle and display these warnings yourself.fare
: If present, contains the total fare (that is, the total ticket costs) on this route. This property is only returned for transit requests and only for routes where fare information is available for all transit legs. The information includes:currency
: An ISO 4217 currency code indicating the currency that the amount is expressed in.value
: The total fare amount, in the currency specified above.text
: The total fare amount, formatted in the requested language.
Below is an example of fare information within a route:
"routes" : [ { "bounds" : { "northeast" : { "lat" : 37.8079996, "lng" : -122.4074334 }, "southwest" : { "lat" : 37.7881005, "lng" : -122.4203553 } }, "copyrights" : "Map data ©2015 Google", "fare" : { "currency" : "USD", "value" : 6 "text" : "$6.00" }, ... }]
Legs
Each element in the legs
array specifies a single leg
of the journey from the origin to the destination in the calculated
route. For routes that contain no waypoints, the route will consist
of a single "leg," but for routes that define one or more
waypoints, the route will consist of one or more legs, corresponding
to the specific legs of the journey.
Each leg within the legs
field(s) may contain
the following fields:
steps[]
contains an array of steps denoting information about each separate step of the leg of the journey. (See Directions Steps below.)distance
indicates the total distance covered by this leg, as a field with the following elements:value
indicates the distance in meterstext
contains a human-readable representation of the distance, displayed in units as used at the origin (or as overridden within theunits
parameter in the request). (For example, miles and feet will be used for any origin within the United States.) Note that regardless of what unit system is displayed as text, thedistance.value
field always contains a value expressed in meters.
These fields may be absent if the distance is unknown.
duration
indicates the total duration of this leg, as a field with the following elements:value
indicates the duration in seconds.text
contains a human-readable representation of the duration.
These fields may be absent if the duration is unknown.
duration_in_traffic
indicates the total duration of this leg. This value is an estimate of the time in traffic based on current and historical traffic conditions. See thetraffic_model
request parameter for the options you can use to request that the returned value is optimistic, pessimistic, or a best-guess estimate. The duration in traffic is returned only if all of the following are true:- The request includes a valid API key, or a valid Google Maps Platform Premium Plan client ID and signature.
- The request does not include stopover waypoints. If the request
includes waypoints, they must be prefixed with
via:
to avoid stopovers. - The request is specifically for driving directions—the
mode
parameter is set todriving
. - The request includes a
departure_time
parameter. - Traffic conditions are available for the requested route.
The
duration_in_traffic
contains the following fields:value
indicates the duration in seconds.text
contains a human-readable representation of the duration.
arrival_time
contains the estimated time of arrival for this leg. This property is only returned for transit directions. The result is returned as aTime
object with three properties:value
the time specified as a JavaScriptDate
object.text
the time specified as a string. The time is displayed in the time zone of the transit stop.time_zone
contains the time zone of this station. The value is the name of the time zone as defined in the IANA Time Zone Database, e.g. "America/New_York".
departure_time
contains the estimated time of departure for this leg, specified as aTime
object. Thedeparture_time
is only available for transit directions.start_location
contains the latitude/longitude coordinates of the origin of this leg. Because the Directions API calculates directions between locations by using the nearest transportation option (usually a road) at the start and end points,start_location
may be different than the provided origin of this leg if, for example, a road is not near the origin.end_location
contains the latitude/longitude coordinates of the given destination of this leg. Because the Directions API calculates directions between locations by using the nearest transportation option (usually a road) at the start and end points,end_location
may be different than the provided destination of this leg if, for example, a road is not near the destination.start_address
contains the human-readable address (typically a street address) resulting from reverse geocoding thestart_location
of this leg.end_address
contains the human-readable address (typically a street address) from reverse geocoding theend_location
of this leg.
Steps
Each element in the steps
array defines a single step
of the calculated directions. A step is the most atomic unit of a
direction's route, containing a single step describing a specific, single
instruction on the journey. E.g. "Turn left at W. 4th St." The step not
only describes the instruction but also contains distance and duration
information relating to how this step relates to the following step.
For example, a step denoted as "Merge onto I-80 West" may contain a
duration of "37 miles" and "40 minutes," indicating that the next step
is 37 miles/40 minutes from this step.
When using the Directions API to search for transit directions, the steps
array will include additional transit details
in the form of a transit_details
array. If the directions
include multiple modes of transportation, detailed directions will be
provided for walking or driving steps in an inner steps
array.
For example, a walking step will include directions from the start and end
locations: "Walk to Innes Ave & Fitch St". That step will include
detailed walking directions for that route in the inner steps
array, such as: "Head north-west", "Turn left onto Arelious Walker", and
"Turn left onto Innes Ave".
Each step within the steps
field(s) may contain
the following fields:
html_instructions
contains formatted instructions for this step, presented as an HTML text string. (Corresponds toinstructions
in the Directions.Step interface.)distance
contains the distance covered by this step until the next step. (See the discussion of this field in Directions Legs above.) This field may be undefined if the distance is unknown.duration
contains the typical time required to perform the step, until the next step. (See the description in Directions Legs above.) This field may be undefined if the duration is unknown.start_location
contains the location of the starting point of this step, as a single set oflat
andlng
fields.end_location
contains the location of the last point of this step, as a single set oflat
andlng
fields.maneuver
contains the action to take for the current step (turn left, merge, straight, etc.). This field is used to determine which icon to display, and can contain one of the following values:turn-slight-left
,turn-sharp-left
,uturn-left
,turn-left
,turn-slight-right
,turn-sharp-right
,uturn-right
,turn-right
,straight
,ramp-left
,ramp-right
,merge
,fork-left
,fork-right
,ferry
,ferry-train
,roundabout-left
,roundabout-right
. Values in this list are subject to change. (Not available through the Directions.Step interface.)polyline
contains a singlepoints
object that holds an encoded polyline representation of the step. This polyline is an approximate (smoothed) path of the step. (Corresponds topath
in the Directions.Step interface.)steps
contains detailed directions for walking or driving steps in transit directions. Substeps are only available whentravel_mode
is set to "transit". The innersteps
array is of the same type assteps
.transit_details
contains transit specific information. This field is only returned withtravel_mode
is set to "transit". See Transit Details below. (Corresponds totransit
in the Directions.Step interface.)travel_mode
contains the type of travel mode used.
Transit Details
Transit directions return additional information that is not relevant for
other modes of transportation. These additional properties are exposed
through the transit_details
object, returned as a field of
an element in the steps[]
array. From the
TransitDetails
object you can access additional information
about the transit stop, transit line and transit agency.
A transit_details
object may contain the following fields:
arrival_stop
anddeparture_stop
contains information about the stop/station for this part of the trip. Stop details can include:name
the name of the transit station/stop. eg. "Union Square".location
the location of the transit station/stop, represented as alat
andlng
field.
arrival_time
anddeparture_time
contain the arrival or departure times for this leg of the journey, specified as the following three properties:text
the time specified as a string. The time is displayed in the time zone of the transit stop.value
the time specified as Unix time, or seconds since midnight, January 1, 1970 UTC.time_zone
contains the time zone of this station. The value is the name of the time zone as defined in the IANA Time Zone Database, e.g. "America/New_York".
headsign
specifies the direction in which to travel on this line, as it is marked on the vehicle or at the departure stop. This will often be the terminus station.headway
specifies the expected number of seconds between departures from the same stop at this time. For example, with aheadway
value of 600, you would expect a ten minute wait if you should miss your bus.num_stops
contains the number of stops in this step, counting the arrival stop, but not the departure stop. For example, if your directions involve leaving from Stop A, passing through stops B and C, and arriving at stop D,num_stops
will return 3.trip_short_name
contains the text that appears in schedules and sign boards to identify a transit trip to passengers. The text should uniquely identify a trip within a service day. For example, "538" is thetrip_short_name
of the Amtrak train that leaves San Jose, CA at 15:10 on weekdays to Sacramento, CA.line
contains information about the transit line used in this step, and may include the following properties:name
contains the full name of this transit line. eg. "7 Avenue Express".short_name
contains the short name of this transit line. This will normally be a line number, such as "M7" or "355".color
contains the color commonly used in signage for this transit line. The color will be specified as a hex string such as: #FF0033.agencies
is an array containing a singleTransitAgency
object. TheTransitAgency
object provides information about the operator of the line, including the following properties:name
contains the name of the transit agency.phone
contains the phone number of the transit agency.url
contains the URL for the transit agency.
You must display the names and URLs of the transit agencies servicing the trip results.
url
contains the URL for this transit line as provided by the transit agency.icon
contains the URL for the icon associated with this line.text_color
contains the color of text commonly used for signage of this line. The color will be specified as a hex string.vehicle
contains the type of vehicle used on this line. This may include the following properties:name
contains the name of the vehicle on this line. eg. "Subway."type
contains the type of vehicle that runs on this line. See the Vehicle Type documentation for a complete list of supported values.icon
contains the URL for an icon associated with this vehicle type.local_icon
contains the URL for the icon associated with this vehicle type, based on the local transport signage.
Vehicle Type
The vehicle.type
property may return any of the following
values:
Value | Definition |
---|---|
RAIL |
Rail. |
METRO_RAIL |
Light rail transit. |
SUBWAY |
Underground light rail. |
TRAM |
Above ground light rail. |
MONORAIL |
Monorail. |
HEAVY_RAIL |
Heavy rail. |
COMMUTER_TRAIN |
Commuter rail. |
HIGH_SPEED_TRAIN |
High speed train. |
LONG_DISTANCE_TRAIN |
Long distance train. |
BUS |
Bus. |
INTERCITY_BUS |
Intercity bus. |
TROLLEYBUS |
Trolleybus. |
SHARE_TAXI |
Share taxi is a kind of bus with the ability to drop off and pick up passengers anywhere on its route. |
FERRY |
Ferry. |
CABLE_CAR |
A vehicle that operates on a cable, usually on the ground. Aerial cable
cars may be of the type GONDOLA_LIFT . |
GONDOLA_LIFT |
An aerial cable car. |
FUNICULAR |
A vehicle that is pulled up a steep incline by a cable. A Funicular typically consists of two cars, with each car acting as a counterweight for the other. |
OTHER |
All other vehicles will return this type. |
Available Travel Modes
The response field available_travel_modes
contains an array of
available travel modes. The Directions service returns this field when a request specifies a
travel mode
that is not currently available and therefore gets no results. The service
returns an array containing the travel modes that are available in the countries of the given set of
waypoints. The field is not returned if any of the waypoints are via:
waypoints.
For example, try this request:
https://maps.googleapis.com/maps/api/directions/json?
&mode=transit
&origin=frontera+el+hierro&destination=la+restinga+el+hierro
&departure_time=1399995076&
key=YOUR_API_KEY
The example produces this response:
{ "available_travel_modes" : [ "DRIVING", "BICYCLING", "WALKING" ], "geocoded_waypoints" : [ { "geocoder_status" : "OK", "partial_match" : true, "place_id" : "ChIJwZNMti1fawwRO2aVVVX2yKg", "types" : [ "locality", "political" ] }, { "geocoder_status" : "OK", "partial_match" : true, "place_id" : "ChIJ3aPgQGtXawwRLYeiBMUi7bM", "types" : [ "locality", "political" ] } ], "routes" : [], "status" : "ZERO_RESULTS" }
The sensor
Parameter
The Google Maps API previously required that you include the
sensor
parameter to indicate whether your application used a
sensor to determine the user's location. This parameter is no longer
required.