> ## Content Index
> Fetch the complete content index at: https://blog.afi.io/llms.txt
> Use this file to discover other available public pages before exploring further.

# Google ODRD: Routes Preferred ComputeRoutes API
- URL: https://blog.afi.io/blog/google-odrd-routes-preferred-computeroutes-api/
- Published: 2023-09-22T09:19:11.000Z
- Updated: 2026-07-24T05:55:01.000Z
- Description: Calling the Google ODRD: Routes Preferred ComputeRoutes API to get the fastest route between two points.
- Author: Afian Anwar
- Tags: googlemaps

The first Google Mobility API we'll look at is [Routes Preferred](https://developers.google.com/maps/documentation/routes%5Fpreferred?ref=blog.afi.io) which is actually two separate APIs - ComputeRoutes, which we will look at in detail here and ComputeRouteMatrix, which we will touch on in the [next post](https://afi.io/blog/google-lmfs-routes-preferred-computeroutematrix-api/?ref=blog.afi.io).

Part 1: [Google Mobility: An introduction to Google ODRD, LMFS and Cloud Fleet Routing APIs ](https://www.afi.io/blog/google-mobility-an-introduction-to-google-odrd-lmfs-and-cloud-fleet-routing-apis/?ref=blog.afi.io)  
**Part 2: Google ODRD: Routes Preferred ComputeRoutes API (this article)**  
Part 3: [Google LMFS: Routes Preferred ComputeRouteMatrix API](https://afi.io/blog/google-lmfs-routes-preferred-computeroutematrix-api/?ref=blog.afi.io)  
Part 4: [Google Cloud Fleet Routing: OptimizeTours API](https://afi.io/blog/google-cloud-fleet-routing-optimizetours-api/?ref=blog.afi.io)  
Part 5: [Google ODRD: Navigation SDK](https://www.afi.io/blog/google-odrd-navigation-sdk/?ref=blog.afi.io)

Think of ComputeRoutes as an enhanced version of the [Google Directions API](https://developers.google.com/maps/documentation/directions/overview?ref=blog.afi.io). Like the Directions API, it calculates the best route from a start point to an end point, including any waypoints along the way. However, ComputeRoutes offers numerous performance enhancements compared to Directions. It's typically faster, provides more precise estimated times of arrival (ETAs), and employs [field masks](https://developers.google.com/maps/documentation/routes%5Fpreferred/choose%5Ffields?ref=blog.afi.io) (through the `X-Goog-FieldMask` header) to reduces latency by allowing you to specify which fields you want the API to return.

💡

To use the ComputeRoutes API you need a valid Routes Preferred API key. Right now, availability is limited to larger enterprise customers. Please contact a [Google Maps Partner](https://cloud.google.com/find-a-partner/?expertises=Google%20Maps%20Platform&ref=blog.afi.io) for access. Once approved, [follow this guide](https://developers.google.com/maps/documentation/routes%5Fpreferred/get%5Fstarted?ref=blog.afi.io) to retrieve your API key.

Initially bundled with [On Demand Rides and Deliveries](https://developers.google.com/maps/documentation/transportation-logistics/on-demand-rides-deliveries-solution?ref=blog.afi.io) (ODRD), the ComputeRoutes API can now be used on its own or in combination with other Google Mobility APIs.

### ODRD / Routes Preferred ComputeRoutes example

We'll start with a simple example of a point to point route from East Vancouver (circle marker) to Vancouver Airport (stop 1).

![Example of an ODRD RoutesPreferred ComputeRoute route ](https://storage.ghost.io/c/c6/4d/c64da7e8-63a6-4cff-acdc-2782a6ebc377/content/images/2023/09/Screen-Shot-2023-09-19-at-11.48.50-AM.png)

A route created using the Route Preferred ComputeRoutes API

**Endpoint** `POST` [https://routespreferred.googleapis.com/v1:computeRoutes](https://routespreferred.googleapis.com/v1:computeRoutes?ref=blog.afi.io)

**Headers**  
Content-Type: *application/json*  
X-Goog-Api-Key: *YOUR\_API\_KEY* (contact a [Google Maps Partner](https://cloud.google.com/find-a-partner/?expertises=Google%20Maps%20Platform&ref=blog.afi.io) for access)  
X-Goog-FieldMask: *routes.duration, routes.distanceMeters, routes.polyline*

**Body**

```JSON
{
	"origin": {
		"location": {
			"latLng": {
				"latitude": 49.2806962,
				"longitude": -123.0828679
			}
		}
	},
	"destination": {
		"location": {
			"latLng": {
				"latitude": 49.1951165,
				"longitude": -123.1814231
			}
		}
	},
	"travelMode": "DRIVE",
	"polylineQuality": "OVERVIEW",
	"departureTime": "2023-09-25T15:00:00Z"
}
```

`origin.location.latLng` are the coordinates of the route's start location.

`destination.location.latLng` are the coordinates of the route's end location.

`travelMode` refers to the mode of transport ("DRIVE", "WALK", "TRANSIT" or "BICYCLE"). Different modes use different routes (e.g. choosing "BICYCLE" means that the route chosen will prioritize bike paths), have different travel speeds and as such, result in different ETAs.

`routingPreference` offers three choices: "TRAFFIC\_UNAWARE," "TRAFFIC\_AWARE," and "TRAFFIC\_AWARE\_OPTIMAL." When you select "TRAFFIC\_AWARE," the routing algorithm factors in real-time traffic conditions when calculating routes. On the other hand, "TRAFFIC\_AWARE\_OPTIMAL" also considers traffic but prioritizes speed over absolute precision, resulting in faster route calculations (although slightly less accuracy) due to certain optimizations designed to reduce latency. If you opt for "TRAFFIC\_UNAWARE," the routing relies solely on posted speed limits, which means this option is suitable for deliveries in rural areas or cities where traffic congestion is rarely an issue.

`polylineQuality` lets you specify the resolution of the encoded polyline e.g. " used to draw the route on a map."HIGH\_QUALITY" returns a polyline with a large number of points at the expense of speed while "OVERVIEW" returns one with less points but is much faster. Generally speaking, if you are just drawing the route on a static map and not allowing the user to zoom in, the "OVERVIEW" option works just fine. You can use Google's [polyline decoding tool](https://developers.google.com/maps/documentation/routes/polylinedecoder?ref=blog.afi.io) to view the encoded polyline string on the map.

`departureTime` , when combined with `routingPreference`: "TRAFFIC\_AWARE", is probably the single most important field in the input. It allows you to specify the start time of the route as a datetime string in [RFC3339](https://medium.easyread.co/understanding-about-rfc-3339-for-datetime-formatting-in-software-engineering-940aa5d5f68a?ref=blog.afi.io) UTC "Zulu" format e.g. "2023-09-25T15:00:00Z" so that the travel time `duration` returned by the API takes predicted "real time" traffic into account. The "Z" in the string stands for "Zulu" (GMT +0). Since our route is in Vancouver which is on Pacific Standard Time (GMT +7), "2023-09-25T15:00:00Z" resolves to 8 am on 25th September, 2023\. 

Note: If `departureTime` is left empty, it defaults to the time that the request was made. Also, if you set this value to a time in the past, then the request fails.

🌎

This is a collection of what I feel are the most important fields to use when making a ComputeRoutes call. The [official documentation for Routes Preferred / Compute Routes](https://developers.google.com/maps/documentation/routes%5Fpreferred/reference/rest/v1/TopLevel/computeRoutes?ref=blog.afi.io) has the complete list.

The above API call returns the following:

**Output**

```JSON
{
    "routes": [
        {
            "distanceMeters": 16797,
            "duration": "1802s",
            "polyline": {
                "encodedPolyline": "ecxkH|rfnV?sAfARl@TpBpAz@Rh@F`CHr@ClCDBgChBBJo`@hSHjNJf@Bb@JhELnD@tAKPIzPJtGHPHvNRhGIdIB~@Yj@g@R[Vm@h@}A\\k@j@e@r@Qn@ChUZlD@tF@|@F`HNxCBpFFVMd`@ZRNxIDvBL^FNGdEp@bBLxCJ~E@nIJZP`FHCzH?jFFTSrn@Kb@GtOEjOFj@Ol^Gb@S~Y?lDi@~j@IdGMrGUfQbEJtOPvSRjBHh\\d@ra@f@rMPxQ\\LBt@EzCxIPVxB~GFl@nB`GbDrKxDpLnCdJj@|Bj@lBfApCb@xA\\nBNRz@xCzB`Hj@vAj@`AbAfAt@h@xAh@zBp@LJbG~A`PvElAj@v@f@pAxA`A|Ax@pBh@lBJd@`AhIxC|XxBvTz@zHNjBNnDTtETlHBrBBvLEny@EtXGpBSdCQbAk@vBi@xAmCfGWhAe@nGa@vH@tBN`Cd@~CPb@DF"
            }
        }
    ]
}
```

The response from the API is simple enough to understand. `routes` contains a single object with `distanceMeters`, the total distance travelled, `duration`, the total time in seconds taken to complete the route (the ETA at the end point is simply the start time (2023-09-25T15:00:00Z is 08:00:00 Vancouver time which when added to the 1802 seconds `duration` , which gives you an ETA of 08:30:02).

Finally, the encoded polyline from the `polyline.encodedPolyline` field can be used with the [Google Maps Geometry Library](https://developers.google.com/maps/documentation/javascript/geometry?ref=blog.afi.io) to draw the route on a map like so:

### Drawing the route polyline on Google Maps

Starting with a basic HTML template with a map <div/>, import the Geometry library.

```HTML
/* routeMap.html */
<html>
  <head>
    <title>Draw Route</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&v=3.exp&libraries=geometry&callback=Function.prototype"></script>
  </head>
  <body>
    <div id="map" style="height: 600px; width: 100%;"></div>
    
  </body>
</html>
```

Next, inside a script tag next to the map <div/>, create a Google base map and center it at the desired location. The code below calls `initMap()` to create the map and bind it to a div with "map" as its ID.

```HTML
/* routeMap.html */
<script>
var map;

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {
			lat: 49.2578182,
			lng: -123.206304
		},
		zoom: 12 // Adjust the zoom level as needed
	});
}

initMap();
</script>
```

Add two markers, one for the origin and the other for the destination. This code should be added after the call to `initMap()`.

```HTML
/* routeMap.html */
<script>
var startMarker = new google.maps.Marker({
	position: {
		lat: 49.2806962,
		lng: -123.0828679
	},
	map: map,
	title: 'Start'
});

var endMarker = new google.maps.Marker({
	position: {
		lat: 49.1951165,
		lng: -123.1814231
	},
	map: map,
	title: 'End'
});
</script>
```

Lastly, decode the polyline string, style it, and add it to the map.

```HTML
/* routeMap.html */
<script>
var decodedPath = google.maps.geometry.encoding.decodePath("ecxkH|rfnV?sAfARl@TpBpAz@Rh@F`CHr@ClCDBgChBBJo`@hSHjNJf@Bb@JhELnD@tAKPIzPJtGHPHvNRhGIdIB~@Yj@g@R[Vm@h@}A\\k@j@e@r@Qn@ChUZlD@tF@|@F`HNxCBpFFVMd`@ZRNxIDvBL^FNGdEp@bBLxCJ~E@nIJZP`FHCzH?jFFTSrn@Kb@GtOEjOFj@Ol^Gb@S~Y?lDi@~j@IdGMrGUfQbEJtOPvSRjBHh\\d@ra@f@rMPxQ\\LBt@EzCxIPVxB~GFl@nB`GbDrKxDpLnCdJj@|Bj@lBfApCb@xA\\nBNRz@xCzB`Hj@vAj@`AbAfAt@h@xAh@zBp@LJbG~A`PvElAj@v@f@pAxA`A|Ax@pBh@lBJd@`AhIxC|XxBvTz@zHNjBNnDTtETlHBrBBvLEny@EtXGpBSdCQbAk@vBi@xAmCfGWhAe@nGa@vH@tBN`Cd@~CPb@DF");

var polyline = new google.maps.Polyline({
	path: decodedPath,
	geodesic: true,
	strokeColor: '#4285F4', // Adjust the color as needed
	strokeOpacity: 0.9,
	strokeWeight: 3 // Adjust the line thickness as needed
});

polyline.setMap(map);
</script>
```

If everything worked correctly you should see the route clearly displayed on the map, with a marker at the start and end locations ([full source code](https://gist.github.com/afian/8a3c456f632002e7c85b27c8b47187c0?ref=blog.afi.io)).

![The route polyline returned by the Google ODRD Routes Preferred ComputeRoutes API](https://storage.ghost.io/c/c6/4d/c64da7e8-63a6-4cff-acdc-2782a6ebc377/content/images/2023/09/Screen-Shot-2023-09-21-at-7.18.04-PM.png)

The route polyline returned by the Google Routes Preferred ComputeRoutes API

This concludes my introduction to the Routes Preferred ComputeRoutes API. In the next post, we'll look at another popular Routes Preferred API, ComputeRouteMatrix, which is used to generate travel time matrices with real time traffic.

**This article was written by** [**Afi Labs**](https://afi.io/?ref=blog.afi.io)**, a Google Maps Platform Premier Partner and reseller. We build route optimization, navigation, and fleet tracking software on Google Maps, and offer volume pricing on GMP licensing.** [**Talk to an engineer**](https://afi.io/contact%5Fus?ref=blog.afi.io) **or** [**follow Afian on LinkedIn**](https://www.linkedin.com/in/afian-anwar/?ref=blog.afi.io)**.**

Next: [Part 3: Google LMFS: Routes Preferred ComputeRouteMatrix API](https://afi.io/blog/google-lmfs-routes-preferred-computeroutematrix-api/?ref=blog.afi.io)