Actualiza la ubicación de un vehículo de entrega
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Approaches
Para obtener el mejor rendimiento con Fleet Engine, proporciónale un flujo de actualizaciones de la ubicación del vehículo al menos una vez por minuto y, como máximo, una vez cada 5 segundos.
Usa cualquiera de las siguientes formas para proporcionar estas actualizaciones:
- Usa el SDK de Driver: Es la opción más sencilla.
- Usar código personalizado: Es útil si las ubicaciones se retransmiten a través de tu backend o si usas dispositivos que no son Android ni iOS. En este documento, se explica ese enfoque.
Independientemente de cómo proporciones las actualizaciones de ubicación del vehículo, tu backend es responsable de actualizar Fleet Engine cuando un vehículo de reparto está en camino a una parada y cuando llega a una parada. Esto incluye el depósito en sí. Fleet Engine no detecta estos eventos automáticamente.
Ejemplos de actualización de la ubicación del vehículo
Puedes usar la biblioteca de gRPC de Java para actualizar la ubicación de un vehículo en Fleet Engine o usar REST.
Java
static final String PROJECT_ID = "my-delivery-co-gcp-project";
static final String VEHICLE_ID = "vehicle-8241890";
DeliveryServiceBlockingStub deliveryService =
DeliveryServiceGrpc.newBlockingStub(channel);
// Vehicle settings
String vehicleName = "providers/" + PROJECT_ID + "/deliveryVehicles/" + VEHICLE_ID;
DeliveryVehicle myDeliveryVehicle = DeliveryVehicle.newBuilder()
.setLastLocation(DeliveryVehicleLocation.newBuilder()
.setSupplementalLocation(LatLng.newBuilder()
.setLatitude(37.3382)
.setLongitude(121.8863))
.setSupplementalLocationTime(now())
.setSupplementalLocationSensor(DeliveryVehicleLocationSensor.CUSTOMER_SUPPLIED_LOCATION)
.setSupplementalLocationAccuracy(DoubleValue.of(15.0))) // Optional
.build();
// DeliveryVehicle request
UpdateDeliveryVehicleRequest updateDeliveryVehicleRequest =
UpdateDeliveryVehicleRequest.newBuilder() // No need for the header
.setName(vehicleName)
.setDeliveryVehicle(myDeliveryVehicle)
.setUpdateMask(FieldMask.newBuilder()
.addPaths("last_location"))
.build();
try {
DeliveryVehicle updatedDeliveryVehicle =
deliveryService.updateDeliveryVehicle(updateDeliveryVehicleRequest);
} catch (StatusRuntimeException e) {
Status s = e.getStatus();
switch (s.getCode()) {
case NOT_FOUND:
break;
case PERMISSION_DENIED:
break;
}
return;
}
REST
PATCH https://fleetengine.googleapis.com/v1/providers/<project_id>/deliveryVehicles/<id>?updateMask=last_location
Detalles de la solicitud
El cuerpo de la solicitud debe contener una entidad DeliveryVehicle
que especifique los campos de la siguiente manera:
Campos obligatorios:
Campo | Valor |
lastLocation.supplementalLocation |
Es la ubicación del vehículo. |
lastLocation.supplementalLocationTime |
Es la última marca de tiempo conocida en la que el vehículo estuvo en esta ubicación. |
lastLocation.supplementalLocationSensor |
Se debe completar con CUSTOMER_SUPPLIED_LOCATION . |
Campos opcionales:
Campo | Valor |
lastLocation.supplementalLocationAccuracy |
Precisión de la ubicación proporcionada, en metros. |
# Set JWT, PROJECT_ID, VEHICLE_ID, TASK1_ID, and TASK2_ID in the local
# environment
curl -X PATCH "https://fleetengine.googleapis.com/v1/providers/${PROJECT_ID}/deliveryVehicles/${VEHICLE_ID}?updateMask=remainingVehicleJourneySegments" \
-H "Content-type: application/json" \
-H "Authorization: Bearer ${JWT}" \
--data-binary @- << EOM
{
"lastLocation": {
"supplementalLocation": {"latitude": 12.1, "longitude": 14.5},
"supplementalLocationTime": "$(date -u --iso-8601=seconds)",
"supplementalLocationSensor": "CUSTOMER_SUPPLIED_LOCATION",
"supplementalLocationAccuracy": 15
}
}
EOM
¿Qué sigue?
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-08-31 (UTC)
[null,null,["Última actualización: 2025-08-31 (UTC)"],[[["\u003cp\u003eBefore making vehicle requests, review the requirements outlined in the Vehicle requests section of the Introduction.\u003c/p\u003e\n"],["\u003cp\u003eProvide vehicle location updates to Fleet Engine at least every minute and at most every 5 seconds, either using the Driver SDK (simplest) or custom code for backend integration or non-Android/iOS devices.\u003c/p\u003e\n"],["\u003cp\u003eYour backend is responsible for notifying Fleet Engine of vehicle status changes, including en route and arrival at stops, as this is not automatically detected.\u003c/p\u003e\n"],["\u003cp\u003eVehicle location updates can be implemented using the Java gRPC library or REST, with required and optional fields for providing accurate location data and timestamps.\u003c/p\u003e\n"]]],["Vehicle location updates in Fleet Engine can be provided via the Driver SDK or custom code, with updates needed every 5 seconds to 1 minute. Backends must update Fleet Engine when vehicles are en route to or arrive at stops, as it doesn't auto-detect these events. Updates, performed using Java gRPC or REST, require specifying `lastLocation` details like coordinates, timestamp, and sensor as `CUSTOMER_SUPPLIED_LOCATION`. Optionally, location accuracy can also be provided. Ensure to read vehicle request requirements beforehand.\n"],null,["# Update a delivery vehicle location\n\n| **Note:** **Before constructing a vehicle request** , read the requirements under [Vehicle requests](/maps/documentation/mobility/fleet-engine/essentials/vehicles#vehicle_requests) in the Introduction.\n\nApproaches\n----------\n\nFor the best performance with Fleet Engine, provide it with a stream of vehicle\nlocation updates at least once every minute and at most once every 5 seconds.\nUse either of the following ways to provide these updates:\n\n- **Use the [Driver SDK](/maps/documentation/mobility/driver-sdk/scheduled)**: Simplest option.\n- **Use custom code**: useful if locations are relayed through your backend, or if you use devices other than Android or iOS. This document covers that approach.\n\nRegardless of how you provide vehicle location updates, your backend is\nresponsible for updating Fleet Engine when a delivery vehicle is enroute to a\nstop and when it arrives at a stop. This includes the depot itself. Fleet Engine\ndoes not detect these events automatically.\n\nUpdate vehicle location examples\n--------------------------------\n\nYou can use the [Java gRPC library](/maps/documentation/mobility/fleet-engine/essentials/client-libraries-tasks#java) to update a vehicle's location in Fleet\nEngine, or use REST. \n\n### Java\n\n static final String PROJECT_ID = \"my-delivery-co-gcp-project\";\n static final String VEHICLE_ID = \"vehicle-8241890\";\n\n DeliveryServiceBlockingStub deliveryService =\n DeliveryServiceGrpc.newBlockingStub(channel);\n\n // Vehicle settings\n String vehicleName = \"providers/\" + PROJECT_ID + \"/deliveryVehicles/\" + VEHICLE_ID;\n DeliveryVehicle myDeliveryVehicle = DeliveryVehicle.newBuilder()\n .setLastLocation(DeliveryVehicleLocation.newBuilder()\n .setSupplementalLocation(LatLng.newBuilder()\n .setLatitude(37.3382)\n .setLongitude(121.8863))\n .setSupplementalLocationTime(now())\n .setSupplementalLocationSensor(DeliveryVehicleLocationSensor.CUSTOMER_SUPPLIED_LOCATION)\n .setSupplementalLocationAccuracy(DoubleValue.of(15.0))) // Optional\n .build();\n\n // DeliveryVehicle request\n UpdateDeliveryVehicleRequest updateDeliveryVehicleRequest =\n UpdateDeliveryVehicleRequest.newBuilder() // No need for the header\n .setName(vehicleName)\n .setDeliveryVehicle(myDeliveryVehicle)\n .setUpdateMask(FieldMask.newBuilder()\n .addPaths(\"last_location\"))\n .build();\n\n try {\n DeliveryVehicle updatedDeliveryVehicle =\n deliveryService.updateDeliveryVehicle(updateDeliveryVehicleRequest);\n } catch (StatusRuntimeException e) {\n Status s = e.getStatus();\n switch (s.getCode()) {\n case NOT_FOUND:\n break;\n case PERMISSION_DENIED:\n break;\n }\n return;\n }\n\n### REST\n\n PATCH https://fleetengine.googleapis.com/v1/providers/\u003cproject_id\u003e/deliveryVehicles/\u003cid\u003e?updateMask=last_location\n\n### Request details\n\nThe request body must contain a `DeliveryVehicle` entity that specifies\nfields as follows:\n\n- Required fields:\n\n | Field | Value |\n |-------------------------------------------|------------------------------------------------------------|\n | `lastLocation.supplementalLocation` | The location of the vehicle. |\n | `lastLocation.supplementalLocationTime` | The last known timestamp the vehicle was at this location. |\n | `lastLocation.supplementalLocationSensor` | Should be populated with `CUSTOMER_SUPPLIED_LOCATION`. |\n\n \u003cbr /\u003e\n\n- Optional fields:\n\n | Field | Value |\n |---------------------------------------------|-----------------------------------------------|\n | `lastLocation.supplementalLocationAccuracy` | Accuracy of the supplied location, in meters. |\n\n \u003cbr /\u003e\n\n # Set JWT, PROJECT_ID, VEHICLE_ID, TASK1_ID, and TASK2_ID in the local\n # environment\n curl -X PATCH \"https://fleetengine.googleapis.com/v1/providers/${PROJECT_ID}/deliveryVehicles/${VEHICLE_ID}?updateMask=remainingVehicleJourneySegments\" \\\n -H \"Content-type: application/json\" \\\n -H \"Authorization: Bearer ${JWT}\" \\\n --data-binary @- \u003c\u003c EOM\n {\n \"lastLocation\": {\n \"supplementalLocation\": {\"latitude\": 12.1, \"longitude\": 14.5},\n \"supplementalLocationTime\": \"$(date -u --iso-8601=seconds)\",\n \"supplementalLocationSensor\": \"CUSTOMER_SUPPLIED_LOCATION\",\n \"supplementalLocationAccuracy\": 15\n }\n }\n EOM\n\nWhat's next\n-----------\n\n- [Get a delivery vehicle](/maps/documentation/mobility/fleet-engine/essentials/vehicles/scheduled-tasks-get-vehicle)"]]