Na tác dụng với nước

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”), as place IDs, or as latitude/longitude coordinates

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.

Before you begin

Before you start using the Directions API, you need a project with a billing account and the Directions API enabled. To learn more, see Set up in Cloud Console.

Building your Directions API 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.

As is standard in URLs, all parameters are separated using the ampersand (&) character. All reserved characters (for example the plus sign “+”) must be URL-encoded. The list of parameters and their possible values are enumerated below.

Directions examples

The following request returns driving directions from Toronto, Ontario to Montreal, Quebec.

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.

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:

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.

The following request uses plus codes to return driving directions from H8MW+WP to GCG2+3M in Kolkata, India.

The following request returns driving directions from Glasgow, UK to Perth, UK using place IDs.

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 to transit, you can optionally specify either a departure_time or an arrival_time. If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time). You can also optionally include a transit_mode and/or a transit_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

Caution: Requests using traffic information are billed at a higher rate. Learn more about how Directions API usage is billed.

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 is driving, or is not specified (driving is the default travel mode).
  • The request includes a valid departure_time parameter. The departure_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.

Waypoints

Caution: Requests using more than 10 waypoints (between 11 and 25), or waypoint optimization, are billed at a higher rate. Learn more about billing for Google Maps Platform products.

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:. 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:

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:

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.

Caution: Using the via: prefix to avoid stopovers results in directions that are strict in their interpretation of the waypoint. This interpretation may result in severe detours on the route or ZERO_RESULTS in the response status code if the Directions API is unable to create directions through that point.

The following URL requests waypoints using latitude/longitude coordinates:

Here is the same request, using an encoded polyline:

Note that you can freely intermix a via: specifier with location modifiers. For example:

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.

Inspection of the calculated route will indicate that calculation uses waypoints in the following waypoint order:

“waypoint_order”: [ 3, 2, 0, 1 ] Caution: Requests using waypoint optimization are billed at a higher rate. Learn more about how Google Maps Platform products are billed.

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 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 two-character ccTLD (country code top-level domain) argument specifying the region bias. Most ccTLD codes are identical to ISO 3166-1 alpha-2 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”). See Google Maps Platform Coverage Details for supported regions.

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:

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:

Location Modifiers

Caution: Requests using location modifiers are billed at a higher rate. Learn more about how Directions API usage is billed.

You can use location modifiers to indicate how drivers should approach a particular location, by using the side_of_road parameter to specify which side of the road to use, or by specifying a heading to indicate the correct direction of travel. These modifiers may be freely mixed with the via: modifier for intermediate waypoints.

Specify that routes must pass through a particular side of the road

When specifying a waypoint, you can request that the route go through whichever side of the road the waypoint is biased towards by using the side_of_road: prefix. For example, this directions request will return a long route so that the vehicle ends on the side of the road to which the waypoint was biased:

When using side_of_road: with encoded polylines, the parameter is applied to every location along the polyline.

The side_of_road: modifier may only be used with the following restrictions:

  • The travel mode parameter is driving, or is not specified (driving is the default travel mode).

Specify that routes should have a particular heading

When specifying a waypoint, you can request that the route go through the waypoint in a particular heading. This heading is specified with the prefix heading=X:, where X is an integer degree value between 0 (inclusive) and 360 (exclusive). A heading of 0 indicates North, 90 indicates East, and so on, continuing clockwise. For example, in this directions request the route goes east from the origin, then takes a U-turn:

The heading=X: modifier may only be used with the following restrictions:

  • The travel mode parameter is driving, bicycling, or is not specified (driving is the default travel mode).
  • The side_of_road modifier is not specified for the same location.
  • The location is specified with a latitude/longitude value. You may not use heading with addresses, Place IDs, or encoded polylines.

Directions responses

Directions responses are returned in the format indicated by the output flag within the URL request’s path.

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.

The above example requests JSON output. It’s also possible to request XML output. Select the tabs below to see the sample JSON and XML responses.

Related Posts