API 요청

OptimizeToursRequest 메시지는 OptimizeTours 요청을 하는 데 사용할 수 있습니다.

예: OptimizeTours 요청

클라이언트 라이브러리는 널리 사용되는 여러 프로그래밍 언어로도 제공됩니다. OptimizeTours 요청은 REST 또는 gRPC를 사용하여 실행할 수도 있습니다.

요청하기 전에 다음 매개변수를 환경에 적합한 값으로 바꿉니다.

Go

Go 클라이언트 라이브러리를 사용하여 요청합니다.

import (
	"context"
	"fmt"

	routeoptimization "cloud.google.com/go/maps/routeoptimization/apiv1"
	"google.golang.org/genproto/googleapis/type/latlng"

	rpb "cloud.google.com/go/maps/routeoptimization/apiv1/routeoptimizationpb"
)

func optimizeTours(projectID string) (*rpb.OptimizeToursResponse, error) {
	ctx := context.Background()
	c, err := routeoptimization.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("routeoptimization client: %w", err)
	}
	defer c.Close()

	// See https://pkg.go.dev/cloud.google.com/go/maps/routeoptimization/apiv1/routeoptimizationpb#OptimizeToursRequest.
	req := &rpb.OptimizeToursRequest{
		Parent: "projects/" + projectID,
		Model: &rpb.ShipmentModel{
			Shipments: []*rpb.Shipment{
				&rpb.Shipment{
					Deliveries: []*rpb.Shipment_VisitRequest{
						{ArrivalLocation: &latlng.LatLng{Latitude: 48.880942, Longitude: 2.323866}},
					},
				},
			},
			Vehicles: []*rpb.Vehicle{
				{
					StartLocation: &latlng.LatLng{Latitude: 48.863102, Longitude: 2.341204},
					EndLocation:   &latlng.LatLng{Latitude: 48.86311, Longitude: 2.341205},
				},
			},
		},
	}
	return c.OptimizeTours(ctx, req)
}

자바

Java 클라이언트 라이브러리를 사용하여 요청합니다.

import com.google.maps.routeoptimization.v1.OptimizeToursRequest;
import com.google.maps.routeoptimization.v1.OptimizeToursResponse;
import com.google.maps.routeoptimization.v1.RouteOptimizationClient;
import com.google.maps.routeoptimization.v1.RouteOptimizationSettings;
import com.google.maps.routeoptimization.v1.Shipment;
import com.google.maps.routeoptimization.v1.Shipment.VisitRequest;
import com.google.maps.routeoptimization.v1.ShipmentModel;
import com.google.maps.routeoptimization.v1.Vehicle;
import com.google.type.LatLng;
import java.time.Duration;

public class OptimizeTours {
  public static OptimizeToursResponse optimizeTours(String projectId) throws Exception {
    // Optional: method calls that last tens of minutes may be interrupted
    // without enabling a short keep-alive interval.
    RouteOptimizationSettings clientSettings = RouteOptimizationSettings
        .newBuilder()
        .setTransportChannelProvider(RouteOptimizationSettings
            .defaultGrpcTransportProviderBuilder()
            .setKeepAliveTimeDuration(Duration.ofSeconds(30))
            .build()).build();

    RouteOptimizationClient client = RouteOptimizationClient.create(clientSettings);
    OptimizeToursRequest request =
        OptimizeToursRequest.newBuilder()
            .setParent("projects/" + projectId)
            .setModel(
                ShipmentModel.newBuilder()
                    .addShipments(
                        Shipment.newBuilder()
                            .addPickups(
                                VisitRequest.newBuilder()
                                    .setArrivalLocation(
                                        LatLng.newBuilder().setLatitude(48.8).setLongitude(2.4))))
                    .addVehicles(
                        Vehicle.newBuilder()
                            .setStartLocation(
                                LatLng.newBuilder().setLatitude(48.9).setLongitude(2.5))))
            .build();
    return client.optimizeTours(request);
  }
}

Python

Python 클라이언트는 PyPI에서 사용할 수 있습니다.

pip install google-maps-routeoptimization

Python 클라이언트 라이브러리를 사용하여 요청합니다.

from google.maps import routeoptimization_v1 as ro
from datetime import datetime

client = ro.RouteOptimizationClient()
request = ro.OptimizeToursRequest(
    parent="projects/PROJECT_NUMBER_OR_ID",
    model={
      "shipments": [
         {
          "pickups": [
            {
              "arrival_location": {
                "latitude": 37.738818,
                "longitude": -122.4161
              }
            }
          ],
          "deliveries": [
            {
              "arrival_location": {
                "latitude": 37.79581,
                "longitude": -122.4218856
              }
            }
          ]
        }
      ],
      "vehicles": [
        {
          "start_location": {
            "latitude": 37.738818,
            "longitude": -122.4161
          },
          "end_location": {
            "latitude": 37.738818,
            "longitude": -122.4161
          },
          "cost_per_kilometer": 1.0
        }
      ],
      "global_start_time": datetime.fromisoformat("2024-02-13T00:00:00.000Z"),
      "global_end_time": datetime.fromisoformat("2024-02-14T06:00:00.000Z")
    }
)
response = client.optimize_tours(request=request)
print(response)

Node.js

먼저 Google 지도 플랫폼 담당자에게 Node.js 클라이언트 보관 파일 사본을 요청합니다.

다음 JSON 스니펫을 사용하여 package.json 파일을 구성합니다.

  {
    "name": "route-optimization-example",
    "version": "1.0.0",
    "description": "A RouteOptimization example.",
    "main": "main.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "dependencies": {
      "@googlemaps/routeoptimization": "^0.1.0"
    }
  }

Node.js 클라이언트 라이브러리를 사용하여 요청합니다.

'use strict';

const {RouteOptimizationClient} = require('@googlemaps/routeoptimization').v1;

const routeoptimizationClient = new RouteOptimizationClient();

async function callOptimizeTours() {
  const response = await routeoptimizationClient.optimizeTours({
    "parent": "projects/PROJECT_NUMBER_OR_ID",
    "model": {
      "shipments": [
        {
          "pickups": [
            {
              "arrivalLocation": {
                "latitude": 37.73881799999999,
                "longitude": -122.4161
              }
            }
          ],
          "deliveries": [
            {
              "arrivalLocation": {
                "latitude": 37.79581,
                "longitude": -122.4218856
              }
            }
          ]
        }
      ],
      "vehicles": [
        {
          "startLocation": {
            "latitude": 37.73881799999999,
            "longitude": -122.4161
          },
          "endLocation": {
            "latitude": 37.73881799999999,
            "longitude": -122.4161
          },
          "costPerKilometer": 1.0
        }
      ],
      "globalStartTime": "2024-02-13T00:00:00.000Z",
      "globalEndTime": "2024-02-14T06:00:00.000Z"
    }
  });
  console.log(JSON.stringify(response));
}
callOptimizeTours();

REST

다음 명령어는 RouteOptimization API에 OptimizeTours 요청을 전송하고 응답을 동기식으로 수신합니다.

curl -X POST 'https://routeoptimization.googleapis.com/v1/projects/PROJECT_NUMBER_OR_ID:optimizeTours' \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
--data @- << EOM
{
  "model": {
    "shipments": [
      {
        "pickups": [
          {
            "arrivalLocation": {
              "latitude": 37.73881799999999,
              "longitude": -122.4161
            }
          }
        ],
        "deliveries": [
          {
            "arrivalLocation": {
              "latitude": 37.79581,
              "longitude": -122.4218856
            }
          }
        ]
      }
    ],
    "vehicles": [
      {
        "startLocation": {
          "latitude": 37.73881799999999,
          "longitude": -122.4161
        },
        "endLocation": {
          "latitude": 37.73881799999999,
          "longitude": -122.4161
        },
        "costPerKilometer": 1.0
      }
    ],
    "globalStartTime": "2024-02-13T00:00:00.000Z",
    "globalEndTime": "2024-02-14T06:00:00.000Z"
  }
}
EOM

요청이 완료되면 응답 메시지가 전송됩니다.

다음: 응답 해석하기