Predicting future travel times with the Google Maps APIs

Elena kelareva.

Product Manager, Google Maps APIs

  • If your application is used for scheduling deliveries, and you want to ensure you’ve allowed enough time between deliveries so your drivers won’t be late, you might want to use the pessimistic travel time estimates.
  • On the other hand, if you’re building a thermostat app, and you want the house to be warm by the time your user arrives home from work, you might want to use the optimistic travel time estimate to calculate when the user is likely to arrive.
  • If you want to give your user an estimate of the most likely travel time to their destination, the default best_guess traffic model will give you the most likely travel time considering both current traffic conditions and historical averages.

https://storage.googleapis.com/gweb-cloudblog-publish/images/Predictive_Maps.max-700x700.png

“Taking the guesswork out of knowing how long it will take to drive between homes will help us provide a better customer experience to our users” – Curtis Howell, Product Manager Customer Engagement, Redfin

  • Inside Google Cloud

Related articles

https://storage.googleapis.com/gweb-cloudblog-publish/images/whats_new.max-700x700.jpg

What’s new with Google Cloud

By Google Cloud Content & Editorial • 2-minute read

What’s new with Google Cloud - 2023

By Google Cloud Content & Editorial • 29-minute read

https://storage.googleapis.com/gweb-cloudblog-publish/images/Google_Cloud_AIML_thumbnail.max-700x700.jpg

Shared fate: Protecting customers with generative AI indemnification

By Neal Suggs • 4-minute read

https://storage.googleapis.com/gweb-cloudblog-publish/images/People-of-GC_Jack_Ngare.max-700x700.jpg

“The time is now.” Why this Kenyan Googler is betting on Africa’s tech opportunity

By Google Cloud Content & Editorial • 3-minute read

  • Google Maps Platform
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Web Services
  • Distance Matrix API
  • Documentation

Distance Matrix API request and response

A Distance Matrix API request takes the following form:

where outputFormat may be either of the following values:

  • json (recommended), indicates output in JavaScript Object Notation (JSON); or
  • xml , indicates output as XML.

Certain parameters are required while others are optional. 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.

Required parameters

Destinations.

One or more locations to use as the finishing point for calculating travel distance and time. The options for the destinations parameter are the same as for the origins parameter.

The starting point for calculating travel distance and time. You can supply one or more locations separated by the pipe character (|), in the form of a place ID, an address, or latitude/longitude coordinates:

  • Place ID : If you supply a place ID, you must prefix it with place_id: .
  • Address : If you pass an address, the service geocodes the string and converts it to a latitude/longitude coordinate to calculate distance. This coordinate may be different from that returned by the Geocoding API, for example a building entrance rather than its center. Note: using place IDs is preferred over using addresses or latitude/longitude coordinates. Using coordinates will always result in the point being snapped to the road nearest to those coordinates - which may not be an access point to the property, or even a road that will quickly or safely lead to the destination. Using the address will provide the distance to the center of the building, as opposed to an entrance to the building.
  • Coordinates : If you pass latitude/longitude coordinates, they they will snap to the nearest road. Passing a place ID is preferred. If you do pass coordinates, ensure that no space exists between the latitude and longitude values.
  • global code is a 4 character area code and 6 character or longer local code ( 849VCWC8+R9 is encoded to 849VCWC8%2BR9 ).
  • compound code is a 6 character or longer local code with an explicit location ( CWC8+R9 Mountain View, CA, USA is encoded to CWC8%2BR9%20Mountain%20View%20CA%20USA ).
  • Encoded polylines must be prefixed with enc: and followed by a colon : . For example: origins=enc:gfo}EtohhU:
  • You can also include multiple encoded polylines, separated by the pipe character | . For example: origins=enc:wc~oAwquwMdlTxiKtqLyiK:|enc:c~vnAamswMvlTor@tjGi}L:|enc:udymA{~bxM:

Optional parameters

Arrival_time.

Specifies the desired time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. You can specify either departure_time or arrival_time , but not both. Note that arrival_time must be specified as an integer.

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

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

departure_time

Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. If a departure_time later than 9999-12-31T23:59:59.999999999Z is specified, the API will fall back the departure_time to 9999-12-31T23:59:59.999999999Z. Alternatively, you can specify a value of now, 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 or arrival_time . If neither time is specified, the departure_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. The departure_time must be set to the current time or some time in the future. It cannot be in the past.

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 the Accept-Language header.
  • 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.

For the calculation of distances and directions, you may specify the transportation mode to use. By default, DRIVING mode is used. By default, directions are calculated as driving directions. The following travel modes are supported:

  • driving (default) indicates standard driving directions or distance using the road network.
  • walking requests walking directions or distance via pedestrian paths & sidewalks (where available).
  • bicycling requests bicycling directions or distance via bicycle paths & preferred streets (where available).
  • transit requests directions or distance via public transit routes (where available). Transit trips are available for up to 7 days in the past or 100 days in the future. 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 .

The region code, specified as a ccTLD ("top-level domain") two-character value. 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").

traffic_model

Specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. The traffic_model parameter may only be specified for driving directions where the request includes a departure_time . The available values for this parameter are:

  • best_guess (default) indicates that the returned duration_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 the departure_time is to now.
  • pessimistic indicates that the returned duration_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 returned duration_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.

The default value of best_guess will give the most useful predictions for the vast majority of use cases. It is possible the best_guess travel time prediction may be shorter than optimistic , or alternatively, longer than pessimistic , due to the way the best_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. 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 to transit_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. 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.

Specifies the unit system to use when displaying results.

Request examples

This example uses latitude/longitude coordinates to specify the destination coordinates:

This example uses plus codes to specify the destination coordinates:

This example shows the same request using an encoded polyline:

Traffic information

Traffic information is used when all the following apply (these are the conditions required to receive the duration_in_traffic field in the Distance Matrix 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.

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 Distance Matrix request for driving distances between Boston, MA or Charlestown, MA, and Lexington, MA and Concord, MA. The request includes a departure time, meeting all the requirements to return the duration_in_traffic field in the Distance Matrix response.

Location Modifiers

You can use location modifiers to indicate how drivers should approach a particular location, by using the side_of_road modifier to specify which side of the road to use, or by specifying a heading to indicate the correct direction of travel.

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

When specifying a location, you can request that the calculated route go through whichever side of the road the waypoint is biased towards by using the side_of_road: prefix. For example, this request will return the distance for 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 modifier is applied to every location along the polyline. For example, the two destinations in this request both use the parameter:

The side_of_road: modifier may only be used with this restriction:

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

Specify that calculated routes should have a particular heading

When specifying a location, you can request that the calculated route go through the location 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 request the calculated route goes east from the origin, then takes a U-turn:

The heading=X: modifier may only be used with these 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.

Distance Matrix request and responses

A sample HTTP request is shown below, requesting distance and duration from Vancouver, BC, Canada and from Seattle, WA, USA, to San Francisco, CA, USA and to Victoria, BC, Canada.

This request will return four elements - two origins times two destinations:

Results are returned in rows, each row containing one origin paired with each destination.

DistanceMatrixResponse

Distancematrixstatus.

Status codes returned by service.

  • OK indicates the response contains a valid result.
  • INVALID_REQUEST indicates that the provided request was invalid.
  • MAX_ELEMENTS_EXCEEDED indicates that the product of origins and destinations exceeds the per-query limit.
  • MAX_DIMENSIONS_EXCEEDED indicates that the number of origins or destinations exceeds the per-query limit.
  • 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).
  • 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 Distance Matrix service by your application.
  • UNKNOWN_ERROR indicates a Distance Matrix request could not be processed due to a server error. The request may succeed if you try again.

DistanceMatrixRow

Distancematrixelement.

The total fare for the route.

DistanceMatrixElementStatus

  • NOT_FOUND indicates that the origin and/or destination of this pairing could not be geocoded.
  • ZERO_RESULTS indicates no route could be found between the origin and destination.
  • MAX_ROUTE_LENGTH_EXCEEDED indicates the requested route is too long and cannot be processed.

TextValueObject

An object containing a numeric value and its formatted text representation.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-04-01 UTC.

IMAGES

  1. Getting travel estimates using Google Maps API

    google api estimated travel time

  2. Google Distance Matrix API vs. the TravelTime API: A Comparison

    google api estimated travel time

  3. Full article: Estimating O–D travel time matrix by Google Maps API

    google api estimated travel time

  4. Excel Google Maps Distance and Travel Time Calculator with Directions

    google api estimated travel time

  5. Google Distance Matrix API vs. the TravelTime API: A Comparison

    google api estimated travel time

  6. Estimating time of arrival using GPS service

    google api estimated travel time

VIDEO

  1. Shortest ROUTE to any business from ANYWHERE and estimated time in GOOGLE BUSINESS MAPS

  2. Map the longest possible route. Go!

  3. API: calculate distance between two points

  4. Tahmeed Bus Discover the untamed beauty of East Africa with the comfort and reliability

  5. #zomato asked this #interviewquestions #computerscience

  6. Travel by public bus in Auckland

COMMENTS

  1. Using Google Maps API to get travel time data

    25. Yep, this is definitely possible using the API. You can construct a GDirections object without a map or directions div. You can do a load request from A to B and then call the getDuration method to get the total travel time. First you need to create a directions object: // no need to pass map or results div since.

  2. Predicting future travel times with the Google Maps APIs

    Predictive travel time uses historical time-of-day and day-of-week traffic data to estimate travel times at a future date. This makes it easier than ever to predict how long it will take to get somewhere and suggest the best route even when the departure time is far in the future. Since traffic conditions in the future will vary greatly, we ...

  3. Distance Matrix API request and response

    Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. If a departure_time later than 9999-12-31T23:59:59.999999999Z is specified, the API will fall back the departure_time to 9999-12-31T23:59:59.999999999Z. Alternatively, you can specify a value of now, which sets the ...