Send an optimizeTours Request

This example shows how to solve the VRP example by sending an RPC request to the Fleet Routing Service.

REST

The following example sends an optimization request to Cloud Fleet Routing API and gets the optimization solution synchronously.

Before using any of the request data, make the following replacements:

  • project-id: your GCP project ID.

HTTP method and URL:

POST https://cloudoptimization.googleapis.com/v1/projects/project-id:optimizeTours

Request JSON body:

{
"parent": "projects/project-id",
  "model": {
    "shipments": [
      {
        "deliveries": [
          {
            "arrivalLocation": {
              "latitude": 48.880942,
              "longitude": 2.323866
            },
            "duration": "250s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T01:06:40Z",
                "startTime": "1970-01-01T00:50:00Z"
              }
            ]
          }
        ],
        "loadDemands": {
          "weight": {
            "amount": "10"
          }
        },
        "pickups": [
          {
            "arrivalLocation": {
              "latitude": 48.874507,
              "longitude": 2.30361
            },
            "duration": "150s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T00:33:20Z",
                "startTime": "1970-01-01T00:16:40Z"
              }
            ]
          }
        ]
      },
      {
        "deliveries": [
          {
            "arrivalLocation": {
              "latitude": 48.88094,
              "longitude": 2.323844
            },
            "duration": "251s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T01:06:41Z",
                "startTime": "1970-01-01T00:50:01Z"
              }
            ]
          }
        ],
        "loadDemands": {
          "weight": {
            "amount": "20"
          }
        },
        "pickups": [
          {
            "arrivalLocation": {
              "latitude": 48.880943,
              "longitude": 2.323867
            },
            "duration": "151s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T00:33:21Z",
                "startTime": "1970-01-01T00:16:41Z"
              }
            ]
          }
        ]
      }
    ],
    "vehicles": [
      {
        "loadLimits": {
          "weight": {
            "maxLoad": 50
          }
        },
        "endLocation": {
          "latitude": 48.86311,
          "longitude": 2.341205
        },
        "startLocation": {
          "latitude": 48.863102,
          "longitude": 2.341204
        }
      },
      {
        "loadLimits": {
          "weight": {
            "maxLoad": 60
          }
        },
        "endLocation": {
          "latitude": 48.86312,
          "longitude": 2.341215
        },
        "startLocation": {
          "latitude": 48.863112,
          "longitude": 2.341214
        }
      }
    ]
  }
}

To send your request, choose one of these options:

curl

Save the request body in a file named request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://cloudoptimization.googleapis.com/v1/projects/project-id:optimizeTours"

PowerShell

Save the request body in a file named request.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://cloudoptimization.googleapis.com/v1/projects/project-id:optimizeTours" | Select-Object -Expand Content

Once the request finishes successfully, you should get a response that looks similar to the following:

{
  "routes": [
    {
      "vehicleStartTime": "1970-01-01T00:02:11Z",
      "vehicleEndTime": "1970-01-01T01:15:34Z",
      "visits": [
        {
          "isPickup": true,
          "startTime": "1970-01-01T00:16:40Z",
          "detour": "0s",
          "arrivalLoads": [
            {
              "type": "weight"
            }
          ]
        },
        {
          "shipmentIndex": 1,
          "isPickup": true,
          "startTime": "1970-01-01T00:27:35Z",
          "detour": "725s",
          "arrivalLoads": [
            {
              "type": "weight",
              "value": "10"
            }
          ]
        },
        {
          "startTime": "1970-01-01T00:50:00Z",
          "detour": "1345s",
          "arrivalLoads": [
            {
              "type": "weight",
              "value": "30"
            }
          ]
        },
        {
          "shipmentIndex": 1,
          "startTime": "1970-01-01T00:58:43Z",
          "detour": "1444s",
          "arrivalLoads": [
            {
              "type": "weight",
              "value": "20"
            }
          ]
        }
      ],
      "travelSteps": [
        {
          "duration": "869s",
          "distanceMeters": 4243
        },
        {
          "duration": "505s",
          "distanceMeters": 2480
        },
        {
          "duration": "0s"
        },
        {
          "duration": "273s",
          "distanceMeters": 986
        },
        {
          "duration": "760s",
          "distanceMeters": 3099
        }
      ],
      "vehicleDetour": "4403s",
      "endLoads": [
        {
          "type": "weight"
        }
      ],
      "transitions": [
        {
          "travelDuration": "869s",
          "travelDistanceMeters": 4243,
          "loads": [
            {
              "type": "weight"
            }
          ]
        },
        {
          "travelDuration": "505s",
          "travelDistanceMeters": 2480,
          "loads": [
            {
              "type": "weight",
              "value": "10"
            }
          ]
        },
        {
          "travelDuration": "0s",
          "loads": [
            {
              "type": "weight",
              "value": "30"
            }
          ]
        },
        {
          "travelDuration": "273s",
          "travelDistanceMeters": 986,
          "loads": [
            {
              "type": "weight",
              "value": "20"
            }
          ]
        },
        {
          "travelDuration": "760s",
          "travelDistanceMeters": 3099,
          "loads": [
            {
              "type": "weight"
            }
          ]
        }
      ]
    },
    {
      "vehicleIndex": 1,
      "vehicleStartTime": "1970-01-01T00:00:00Z",
      "vehicleEndTime": "1970-01-01T00:00:00Z",
      "vehicleDetour": "0s"
    }
  ]
}

Java

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.


import com.google.cloud.optimization.v1.FleetRoutingClient;
import com.google.cloud.optimization.v1.OptimizeToursRequest;
import com.google.cloud.optimization.v1.OptimizeToursResponse;
import com.google.protobuf.Duration;
import com.google.protobuf.TextFormat;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * This is an example to send a request to Cloud Fleet Routing synchronous API via Java API Client.
 * A sample sync_request.textproto file can be found in the resources folder.
 */
public class SyncApi {
  public static void callSyncApi() throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectParent = "projects/{YOUR_GCP_PROJECT_ID}";
    String modelPath = "YOUR_MODEL_PATH";
    callSyncApi(projectParent, modelPath);
  }

  public static void callSyncApi(String projectParent, String modelPath) throws Exception {
    int timeoutSeconds = 100;
    InputStream modelInputstream = new FileInputStream(modelPath);
    Reader modelInputStreamReader = new InputStreamReader(modelInputstream);
    OptimizeToursRequest.Builder requestBuilder =
        OptimizeToursRequest.newBuilder()
            .setTimeout(Duration.newBuilder().setSeconds(timeoutSeconds).build())
            .setParent(projectParent);
    TextFormat.getParser().merge(modelInputStreamReader, requestBuilder);
    FleetRoutingClient fleetRoutingClient = FleetRoutingClient.create();
    OptimizeToursResponse response = fleetRoutingClient.optimizeTours(requestBuilder.build());
    System.out.println(response.toString());
  }
}

Python

Before trying this sample, follow the setup instructions for this language on the Client Libraries page.


from google.cloud import optimization_v1

# TODO(developer): Uncomment these variables before running the sample.
# project_id= 'YOUR_PROJECT_ID'


def call_sync_api(project_id: str) -> None:
    """Call the sync api for fleet routing."""
    # Use the default credentials for the environment.
    # Change the file name to your request file.
    request_file_name = "resources/sync_request.json"
    fleet_routing_client = optimization_v1.FleetRoutingClient()

    with open(request_file_name) as f:
        # The request must include the `parent` field with the value set to
        # 'projects/{YOUR_GCP_PROJECT_ID}'.
        fleet_routing_request = optimization_v1.OptimizeToursRequest.from_json(f.read())
        fleet_routing_request.parent = f"projects/{project_id}"
        # Send the request and print the response.
        # Fleet Routing will return a response by the earliest of the `timeout`
        # field in the request payload and the gRPC timeout specified below.
        fleet_routing_response = fleet_routing_client.optimize_tours(
            fleet_routing_request, timeout=100
        )
        print(fleet_routing_response)
        # If you want to format the response to JSON, you can do the following:
        # from google.protobuf.json_format import MessageToJson
        # json_obj = MessageToJson(fleet_routing_response._pb)