Get a route

You can get a route using the Routes API by sending an HTTP POST request to the computeRoutes method (REST) or by calling the ComputeRoutes method (gRPC).

The following example shows the URL of a REST request to the computeRoutes method:

Include your request options in the JSON request body. The request body contains the source and destination locations and any options that you want to set on the route. For more information, see Specify locations and Available route options.

The response contains the fields that you specified in the response field mask by using the URL parameter $fields or field information using the HTTP gRPC header X-Goog-FieldMask. For details, see Choose what information to return.

For an example of a transit route request, see Example: Get a route on transit.

Example: HTTP route request

The following code shows how to construct a request body for a computeRoutes request. In this example, you set the source and destination locations and also specify:

  • A travelMode of DRIVE and a traffic-aware driving route.

  • A set departure time.

  • A language of en-US with imperial distance units.

  • A response field mask in the X-Goog-FieldMask header that specifies to return the following fields in the response:

    • routes.duration
    • routes.distanceMeters
    • routes.polyline.encodedPolyline
curl -X POST -d '{
        "latitude": 37.419734,
        "longitude": -122.0827784
        "latitude": 37.417670,
        "longitude": -122.079595
  "travelMode": "DRIVE",
  "routingPreference": "TRAFFIC_AWARE",
  "departureTime": "2023-10-15T15:01:23.045123456Z",
  "computeAlternativeRoutes": false,
  "routeModifiers": {
    "avoidTolls": false,
    "avoidHighways": false,
    "avoidFerries": false
  "languageCode": "en-US",
  "units": "IMPERIAL"
}' \
-H 'Content-Type: application/json' -H 'X-Goog-Api-Key: YOUR_API_KEY' \
-H 'X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline' \

Example: HTTP route response body

The call above generates the following JSON response:

  "routes": [
      "distanceMeters": 772,
      "duration": "165s",
      "polyline": {
        "encodedPolyline": "ipkcFfichVnP@j@BLoFVwM{E?"

Example: gRPC request

gRPC is a high performance, open source universal RPC framework developed by Google. In gRPC, a client application can directly call methods on a server application on a different machine as if it was a local object.

The following shows an example gRPC request.


package main

import (
  routespb ""

const (
  fieldMask  = "*"
  apiKey     = "INSERT_API_KEY_HERE"
  serverAddr = ""

func main() {
  config := tls.Config{}
  conn, err := grpc.Dial(serverAddr,
  if err != nil {
      log.Fatalf("Failed to connect: %v", err)
  defer conn.Close()
  client := routespb.NewRoutesClient(conn)
  ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  ctx = metadata.AppendToOutgoingContext(ctx, "X-Goog-Api-Key", apiKey)
  ctx = metadata.AppendToOutgoingContext(ctx, "X-Goog-Fieldmask", fieldMask)
  defer cancel()

  // create the origin using a latitude and longitude
  origin := &routespb.Waypoint{
      LocationType: &routespb.Waypoint_Location{
          Location: &routespb.Location{
              LatLng: &latlng.LatLng{
                  Latitude:  37.417670,
                  Longitude: -122.0827784,

  // create the destination using a latitude and longitude
  destination := &routespb.Waypoint{
      LocationType: &routespb.Waypoint_Location{
          Location: &routespb.Location{
              LatLng: &latlng.LatLng{
                  Latitude:  37.417670,
                  Longitude: -122.079595,
  req := &routespb.ComputeRoutesRequest{
      Origin:                   origin,
      Destination:              destination,
      TravelMode:               routespb.RouteTravelMode_DRIVE,
      RoutingPreference:        routespb.RoutingPreference_TRAFFIC_AWARE,
      ComputeAlternativeRoutes: true,
      Units:                    routespb.Units_METRIC,
      RouteModifiers: &routespb.RouteModifiers{
          AvoidTolls:    false,
          AvoidHighways: true,
          AvoidFerries:  true,
      PolylineQuality: routespb.PolylineQuality_OVERVIEW,

  // execute rpc
  resp, err := client.ComputeRoutes(ctx, req)

  if err != nil {
      // "rpc error: code = InvalidArgument desc = Request contains an invalid
      // argument" may indicate that your project lacks access to Routes

  fmt.Printf("Response: %v", resp)



package com.example;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ClientInterceptors;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.NettyChannelBuilder;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RoutesClient {
   // For more detail on inserting API keys, see:
   // For more detail on system parameters (such as FieldMask), see:
   private static final class RoutesInterceptor implements ClientInterceptor {
       private final String apiKey;
       private static final Logger logger = Logger.getLogger(RoutesInterceptor.class.getName());
       private static Metadata.Key API_KEY_HEADER = Metadata.Key.of("x-goog-api-key",
       private static Metadata.Key FIELD_MASK_HEADER = Metadata.Key.of("x-goog-fieldmask",

       public RoutesInterceptor(String apiKey) {
           this.apiKey = apiKey;

       public  ClientCall interceptCall(MethodDescriptor method,
               CallOptions callOptions, Channel next) {
 "Intercepted " + method.getFullMethodName());
           ClientCall call = next.newCall(method, callOptions);
           call = new ForwardingClientCall.SimpleForwardingClientCall(call) {
               public void start(Listener responseListener, Metadata headers) {
                   headers.put(API_KEY_HEADER, apiKey);
                   // Note that setting the field mask to * is OK for testing, but discouraged in
                   // production.
                   // For example, for ComputeRoutes, set the field mask to
                   // "routes.distanceMeters,routes.duration,routes.polyline.encodedPolyline"
                   // in order to get the route distances, durations, and encoded polylines.
                   headers.put(FIELD_MASK_HEADER, "*");
                   super.start(responseListener, headers);
           return call;

   private static final Logger logger = Logger.getLogger(RoutesClient.class.getName());
   private final RoutesGrpc.RoutesBlockingStub blockingStub;

   public RoutesClient(Channel channel) {
       blockingStub = RoutesGrpc.newBlockingStub(channel);

   public static Waypoint createWaypointForLatLng(double lat, double lng) {
       return Waypoint.newBuilder()

   public void computeRoutes() {
       ComputeRoutesRequest request = ComputeRoutesRequest.newBuilder()
               .setOrigin(createWaypointForLatLng(37.420761, -122.081356))
               .setDestination(createWaypointForLatLng(37.420999, -122.086894)).setTravelMode(RouteTravelMode.DRIVE)
       ComputeRoutesResponse response;
       try {
 "About to send request: " + request.toString());
           response = blockingStub.withDeadlineAfter(2000, TimeUnit.MILLISECONDS).computeRoutes(request);
       } catch (StatusRuntimeException e) {
           logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
       }"Response: " + response.toString());

   public void computeRouteMatrix() {
       ComputeRouteMatrixRequest request = ComputeRouteMatrixRequest.newBuilder()
               .addOrigins(RouteMatrixOrigin.newBuilder().setWaypoint(createWaypointForLatLng(37.420761, -122.081356))
               .addOrigins(RouteMatrixOrigin.newBuilder().setWaypoint(createWaypointForLatLng(37.403184, -122.097371)))
                       .setWaypoint(createWaypointForLatLng(37.420999, -122.086894)))
                       .setWaypoint(createWaypointForLatLng(37.383047, -122.044651)))
       Iterator elements;
       try {
 "About to send request: " + request.toString());
           elements = blockingStub.withDeadlineAfter(2000, TimeUnit.MILLISECONDS).computeRouteMatrix(request);
       } catch (StatusRuntimeException e) {
           logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());

       while (elements.hasNext()) {
 "Element response: " +;

   public static void main(String[] args) throws Exception {
       String apiKey = System.getenv("INSERT_API_KEY_HERE");

       // The standard TLS port is 443
       Channel channel = NettyChannelBuilder.forAddress("", 443).build();
       channel = ClientInterceptors.intercept(channel, new RoutesInterceptor(apiKey));

       RoutesClient client = new RoutesClient(channel);


For an example using C#, see Google.Maps.Routing.V2.