### Full HTML Example for Sharing a Journey Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/javascript/share-journey This example demonstrates how to set up an HTML page to display a shared journey, including map initialization, authentication token fetching, and location provider setup. Ensure you replace placeholder values like YOUR_PROVIDER_ID, TRIP_ID, and YOUR_API_KEY. ```html

My Google Maps Demo

``` -------------------------------- ### Run pod install Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/ios/minimum-requirements Execute this command to install the Driver SDK and its dependencies as defined in your Podfile. ```bash pod install ``` -------------------------------- ### Run Pod Install Command Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/setup Execute this command in the terminal to install the Consumer SDK and its dependencies as defined in your Podfile. ```bash pod install ``` -------------------------------- ### Complete AndroidManifest.xml Example Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/android/configure-project A full example of an `AndroidManifest.xml` file including the API key configuration and necessary location permissions. ```xml ``` -------------------------------- ### Start Following a Trip - Objective-C Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/share-journey Initiates following a trip after the view loads. It sets up the map view, configures pickup and dropoff locations, and starts listening for trip updates. ```objectivec /* * MapViewController.m */ - (void)viewDidLoad { [super viewDidLoad]; ... self.mapView = [[GMTCMapView alloc] initWithFrame:CGRectZero]; self.mapView.delegate = self; [self.view addSubview:self.mapView]; } // Handle the callback when the GMTCMapView did initialized. - (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview { self.mapView.pickupLocation = self.selectedPickupLocation; self.mapView.dropoffLocation = self.selectedDropoffLocation; __weak __typeof(self) weakSelf = self; [self startTripBookingWithPickupLocation:self.selectedPickupLocation dropoffLocation:self.selectedDropoffLocation completion:^(NSString *tripName, NSError *error) { __typeof(self) strongSelf = weakSelf; GMTCTripService *tripService = [GMTCServices sharedServices].tripService; // Create a tripModel instance for listening to updates to the trip specified by this trip name. GMTCTripModel *tripModel = [tripService tripModelForTripName:tripName]; // Create a journeySharingSession instance based on the tripModel. GMTCJourneySharingSession *journeySharingSession = [[GMTCJourneySharingSession alloc] initWithTripModel:tripModel]; // Add the journeySharingSession instance on the mapView for updating the UI. [strongSelf.mapView showMapViewSession:journeySharingSession]; // Register for trip update events. [tripModel registerSubscriber:self]; strongSelf.currentTripModel = tripModel; strongSelf.currentJourneySharingSession = journeySharingSession; [strongSelf hideLoadingView]; }]; [self showLoadingView]; } ``` -------------------------------- ### Arrives at stop example Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/journeys/tasks/update-stops This example demonstrates how to notify Fleet Engine that a vehicle has arrived at a stop using a gRPC call. It also shows how to mark subsequent stops as NEW. ```APIDOC ## Arrives at stop example The following examples show how to notify Fleet Engine that a vehicle arrived at the stop, using either the Java gRPC library or an HTTP REST call to `UpdateDeliveryVehicle`. All other stops are marked as new. gRPCREST More ```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 deliveryVehicle = DeliveryVehicle.newBuilder() // Marking the arrival at stop. .addRemainingVehicleJourneySegments(VehicleJourneySegment.newBuilder() .setStop(VehicleStop.newBuilder() .setPlannedLocation(LocationInfo.newBuilder() .setPoint(LatLng.newBuilder() .setLatitude(37.7749) .setLongitude(122.4194))) .addTasks(TaskInfo.newBuilder().setTaskId(TASK1_ID)) .setState(VehicleStop.State.ARRIVED))) // All other remaining stops marked as NEW. .addRemainingVehicleJourneySegments(VehicleJourneySegment.newBuilder() // 2nd stop .setStop(VehicleStop.newBuilder() .setPlannedLocation(LocationInfo.newBuilder() .setPoint(LatLng.newBuilder() .setLatitude(37.3382) .setLongitude(121.8863))) .addTasks(TaskInfo.newBuilder().setTaskId(TASK2_ID)) .setState(VehicleStop.State.NEW))) // Remaining stops must be NEW. .build(); // DeliveryVehicle request UpdateDeliveryVehicleRequest updateDeliveryVehicleRequest = UpdateDeliveryVehicleRequest.newBuilder() // No need for the header .setName(vehicleName) .setDeliveryVehicle(deliveryVehicle) .setUpdateMask(FieldMask.newBuilder() .addPaths("remaining_vehicle_journey_segments")) .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; } ``` ```http `PATCH https://fleetengine.googleapis.com/v1/providers//deliveryVehicles/?updateMask=remainingVehicleJourneySegments` ``` * _< id>_ is a unique identifier for the task. * The request header must contain a field _Authorization_ with the value _Bearer _, where _< token>_ is issued by your server according to the guidelines described in Service account roles and JSON Web tokens. * The request body must contain a `DeliveryVehicle` entity: Example `curl` command: **Note:** This command overwrites any `remainingVehicleJourneySegments` already set on the delivery vehicle. ```bash # 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 { "remainingVehicleJourneySegments": [ { "stop": { "state": "ARRIVED", "plannedLocation": { "point": { "latitude": 37.7749, "longitude": -122.084061 } }, "tasks": [ { "taskId": "${TASK1_ID}" } ] } }, { "stop": { "state": "NEW", "plannedLocation": { "point": { "latitude": 37.3382, "longitude": 121.8863 } }, "tasks": [ { "taskId": "${TASK2_ID}" } ] } } ] } EOM ``` **Experimental:** As an experimental feature, the `LocationInfo` (gRPC or REST) field now supports using `place` (gRPC or REST), either alongside or instead of `LatLng`. ``` -------------------------------- ### Install Fleet Engine Delivery Client Library (Node.js / TypeScript) Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/client-libraries-tasks Install the Fleet Engine Delivery client library for Node.js and TypeScript using npm. This command fetches and installs the necessary package for your project. ```bash npm install @googlemaps/fleetengine-delivery ``` -------------------------------- ### Install CocoaPods Tool Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/ios/minimum-requirements Install the CocoaPods dependency manager by running this command in your terminal. ```bash sudo gem install cocoapods ``` -------------------------------- ### Use gRPC to get a delivery vehicle Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-get-vehicle This example demonstrates how to use the Java gRPC library to look up a vehicle. It includes setting up the project and vehicle IDs, building the request, and handling potential exceptions. ```APIDOC ## Get a delivery vehicle (gRPC) ### Description Retrieves a specific delivery vehicle's data using the gRPC API. ### Method `DeliveryServiceBlockingStub.getDeliveryVehicle` ### Parameters #### Request Body - **name** (string) - Required - The name of the delivery vehicle to retrieve, in the format `providers/{project_id}/deliveryVehicles/{vehicle_id}`. ### Request Example ```java static final String PROJECT_ID = "my-delivery-co-gcp-project"; static final String VEHICLE_ID = "vehicle-8241890"; DeliveryServiceBlockingStub deliveryService = DeliveryServiceGrpc.newBlockingStub(channel); String name = "providers/" + PROJECT_ID + "/deliveryVehicles/" + VEHICLE_ID; GetDeliveryVehicleRequest getVehicleRequest = GetDeliveryVehicleRequest.newBuilder() .setName(name) .build(); try { DeliveryVehicle vehicle = deliveryService.getDeliveryVehicle(getVehicleRequest); } catch (StatusRuntimeException e) { // Handle exceptions like NOT_FOUND or PERMISSION_DENIED } ``` ### Response #### Success Response (200) - **vehicle** (DeliveryVehicle) - The retrieved vehicle entity. ``` -------------------------------- ### Install CocoaPods Tool Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/setup Use this command to install the CocoaPods dependency manager. Ensure you have Ruby installed on your system. ```bash sudo gem install cocoapods ``` -------------------------------- ### Start Following a Trip - Swift Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/share-journey Initiates following a trip after the view loads. It sets up the map view, configures pickup and dropoff locations, and starts listening for trip updates. ```swift /* * MapViewController.swift */ override func viewDidLoad() { super.viewDidLoad() ... self.mapView = GMTCMapView(frame: UIScreen.main.bounds) self.mapView.delegate = self self.view.addSubview(self.mapView) } func mapViewDidInitializeCustomerState(_: GMTCMapView) { self.mapView.pickupLocation = self.selectedPickupLocation self.mapView.dropoffLocation = self.selectedDropoffLocation self.startConsumerMatchWithLocations( pickupLocation: self.mapView.pickupLocation!, dropoffLocation: self.mapView.dropoffLocation! ) { [weak self] (tripName, error) in guard let strongSelf = self else { return } if error != nil { // print error message. return } let tripService = GMTCServices.shared().tripService // Create a tripModel instance for listening the update of the trip // specified by this trip name. let tripModel = tripService.tripModel(forTripName: tripName) // Create a journeySharingSession instance based on the tripModel let journeySharingSession = GMTCJourneySharingSession(tripModel: tripModel) // Add the journeySharingSession instance on the mapView for UI updating. strongSelf.mapView.show(journeySharingSession) // Register for the trip update events. tripModel.register(strongSelf) strongSelf.currentTripModel = tripModel strongSelf.currentJourneySharingSession = journeySharingSession strongSelf.hideLoadingView() } self.showLoadingView() } ``` -------------------------------- ### UpdateVehicle Log Entry Example Source: https://developers.google.com/maps/documentation/mobility/operations/cloud-logging/log-structure This example shows a LogEntry for an UpdateVehicle log, with the RPC request and response details within the jsonPayload field. ```json { "insertId": "c6b85fbc927343fc8a85338c57a65733", "jsonPayload": { "request": { "header": {4}, "updateMask": "deviceSettings", "vehicleId": "uniqueVehicleId", "vehicle": {2} }, "response": { "name": "providers/example-project-id/vehicles/uniqueVehicleId", "availableCapacity": 2, "state": "VEHICLE_STATE_OFFLINE", "maximumCapacity": 2, "vehicleType": {1}, "supportedTrips": {1} }, "@type": "type.googleapis.com/maps.fleetengine.v1.UpdateVehicleLog" }, "resource": { "type": "fleetengine.googleapis.com/Fleet", "labels": {2} }, "timestamp": "2021-01-01T00:00:00.000000000Z", "labels": {2}, "logName": "projects/example-project-id/logs/fleetengine.googleapis.com%2Fupdate_vehicle", "receiveTimestamp": "2021-01-01T00:00:00.000000000Z" } ``` -------------------------------- ### Install Fleet Engine Delivery Client Libraries (Python) Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/client-libraries-tasks Install the google-auth and google-maps-fleetengine-delivery libraries for Python using pip. These libraries are required for interacting with the Fleet Engine API. ```bash pip install google-auth pip install google-maps-fleetengine-delivery ``` -------------------------------- ### Start Listening for Trip Updates (Objective-C) Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/share-journey Register the trip model subscriber to start receiving trip update events. This should be called when the trip begins. ```objectivec /* * MapViewController.m */ - (void)viewDidLoad { [super viewDidLoad]; // Register for trip update events. [self.currentTripModel registerSubscriber:self]; ... } ``` -------------------------------- ### SearchVehicles API Example (Java gRPC) Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-search-vehicle This example demonstrates how to call the `SearchVehicles` API using the Java gRPC client library. It shows how to construct a `SearchVehiclesRequest` with various parameters like pickup/dropoff locations, radius, capacity, trip types, vehicle types, and filtering, and how to process the `SearchVehiclesResponse`. ```APIDOC ## SearchVehicles API Example (Java gRPC) ### Description This example demonstrates how to call the `SearchVehicles` API using the Java gRPC client library. It shows how to construct a `SearchVehiclesRequest` with various parameters like pickup/dropoff locations, radius, capacity, trip types, vehicle types, and filtering, and how to process the `SearchVehiclesResponse`. ### Method `vehicleService.searchVehicles(searchVehiclesRequest)` ### Parameters #### Request Body (Implicitly constructed via `SearchVehiclesRequest.newBuilder()`) - **parent** (String) - Required - The parent resource name, typically in the format `providers/{project_id}`. - **pickupPoint** (TerminalLocation) - Optional - The desired pickup location. - **dropoffPoint** (TerminalLocation) - Optional - The desired dropoff location. - **pickupRadiusMeters** (Integer) - Optional - The radius in meters around the pickup point to search for vehicles. - **count** (Integer) - Optional - The maximum number of vehicles to return. - **minimumCapacity** (Integer) - Optional - The minimum passenger capacity required for the vehicles. - **tripTypes** (List) - Optional - A list of trip types to filter by (e.g., `EXCLUSIVE`). - **vehicleTypes** (List) - Optional - A list of vehicle types to filter by (e.g., `Category.AUTO`). - **currentTripsPresent** (CurrentTripsPresent) - Optional - Specifies whether to include vehicles that are currently on a trip. - **filter** (String) - Optional - A filter string to apply to the search (e.g., `attributes.on_trip="false"`). - **orderBy** (VehicleMatchOrder) - Optional - Specifies the order in which to return the vehicle matches (e.g., `PICKUP_POINT_ETA`). ### Request Example ```java static final String PROJECT_ID = "project-id"; VehicleServiceBlockingStub vehicleService = VehicleService.newBlockingStub(channel); String parent = "providers/" + PROJECT_ID; SearchVehiclesRequest searchVehiclesRequest = SearchVehiclesRequest.newBuilder() .setParent(parent) .setPickupPoint( // Grand Indonesia East Mall TerminalLocation.newBuilder().setPoint( LatLng.newBuilder().setLatitude(-6.195139).setLongitude(106.820826))) .setDropoffPoint( // Balai Sidang Jkt Convention Center TerminalLocation.newBuilder().setPoint( LatLng.newBuilder().setLatitude(-6.213796).setLongitude(106.807195))) .setPickupRadiusMeters(2000) .setCount(10) .setMinimumCapacity(2) .addTripTypes(TripType.EXCLUSIVE) .addVehicleTypes(VehicleType.newBuilder().setCategory(Category.AUTO).build()) .setCurrentTripsPresent(CurrentTripsPresent.ANY) .setFilter("attributes.on_trip=\"false\"") .setOrderBy(VehicleMatchOrder.PICKUP_POINT_ETA) .build(); ``` ### Response #### Success Response (200) - **matches** (List) - A list of `VehicleMatch` objects, each containing a `Vehicle` entity and information about the distance and ETA to the pickup and drop-off points. #### Response Example ```java List vehicleMatches = searchVehicleResponse.getMatchesList(); // Each VehicleMatch contains a Vehicle entity and information about the // distance and ETA to the pickup point and drop-off point. ``` ### Error Handling - `StatusRuntimeException` can be thrown for errors like `NOT_FOUND` or `PERMISSION_DENIED`. ``` -------------------------------- ### Start Listening for Trip Updates (Swift) Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/share-journey Register the trip model callback to start receiving trip update events. This should be called when the trip begins. ```swift /* * MapViewController.swift */ override func viewDidLoad() { super.viewDidLoad() // Register for trip update events. self.currentTripModel.register(self) } ``` -------------------------------- ### Install Fleet Engine and Google Auth with pip Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/client-libraries-trips Install the Fleet Engine client library and the Google authentication library for Python using pip. These are required for interacting with Fleet Engine APIs. ```bash pip install google-auth pip install google-maps-fleetengine ``` -------------------------------- ### Example Viewport for New York City Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/reference/tasks/rest/v1/providers.deliveryVehicles/list This example shows a viewport that fully encloses New York City, demonstrating the structure with specific latitude and longitude values. ```json { "low": { "latitude": 40.477398, "longitude": -74.259087 }, "high": { "latitude": 40.91618, "longitude": -73.70018 } } ``` -------------------------------- ### ListVehicles Java Example Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-list-vehicle This Java example demonstrates how to use the `ListVehicles` method with the Fleet Engine gRPC client library to filter vehicles by type (AUTO) and a custom attribute ('on_trip' set to 'false'). It also shows how to include vehicles that are en route. ```APIDOC ## ListVehicles Java Example ### Description This example filters on both the `vehicle_type` and `attributes` fields using the `filter` string, showing only vehicles of type AUTO and obtaining the LUXURY value for the custom attribute of `class`. You can use the gRPC client libraries or REST. ### Method `VehicleServiceBlockingStub.listVehicles` ### Parameters #### Request Body - **parent** (string) - Required - The parent resource name, in the format `providers/{project_id}`. - **tripTypes** (TripType) - Optional - A list of trip types to filter vehicles by. - **vehicleTypes** (VehicleType) - Optional - A list of vehicle types to filter vehicles by. - **filter** (string) - Optional - A filter string to apply to the query. See Filtering: AIP-160 for syntax. - **includeBackToBack** (boolean) - Optional - Whether to include vehicles that are en route. ### Request Example ```java static final String PROJECT_ID = "project-id"; VehicleServiceBlockingStub vehicleService = VehicleService.newBlockingStub(channel); String parent = "providers/" + PROJECT_ID; ListVehiclesRequest listVehiclesRequest = ListVehiclesRequest.newBuilder() .setParent(parent) .addTripTypes(TripType.EXCLUSIVE) .addVehicleTypes(VehicleType.newBuilder().setCategory(VehicleType.Category.AUTO)) .setFilter("attributes.on_trip=\"false\"") .setIncludeBackToBack(true) // Fleet Engine includes vehicles that are en route. .build(); // Error handling // If matches are returned and the authentication passed, the request completed // successfully try { ListVehiclesResponse listVehiclesResponse = vehicleService.listVehicles(listVehiclesRequest); } catch (StatusRuntimeException e) { Status s = e.getStatus(); switch (s.getCode()) { case NOT_FOUND: break; case PERMISSION_DENIED: break; } return; } ``` ### Response #### Success Response (200) - **vehicles** (List) - A list of vehicles matching the query. - **nextPageToken** (string) - A token to retrieve the next page of results. #### Response Example (Response structure not provided in source) ``` -------------------------------- ### Example Token to Track All Tasks and Vehicles (Scheduled Tasks) Source: https://developers.google.com/maps/documentation/mobility/operations/fleet-tracking/setup This example shows a JWT structure for scheduled tasks, allowing a backend server to track all tasks and vehicles within the fleet. This is useful for periodic fleet status updates and management. ```json { "iat": 1516239022, "exp": 1516242622, "authorization": { "version": 2, "required_scopes": [ "https://www.googleapis.com/auth/fleetengine.vehicles", "https://www.googleapis.com/auth/fleetengine.delivery.vehicles", "https://www.googleapis.com/auth/fleetengine.delivery.tasks" ] } } ``` -------------------------------- ### Session Start Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/reference/consumer_4/android/reference/com/google/android/libraries/mapsplatform/transportation/consumer/sessions/Session Registers the internal manager callbacks for this session if they have not already been registered. ```APIDOC ## start () ### Description Registers the internal manager callbacks for this session if they have not already been registered. ### Method void ### Endpoint N/A (SDK method) ``` -------------------------------- ### Use REST to get a delivery vehicle Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-get-vehicle This example shows how to retrieve a vehicle using a REST API call. It specifies the HTTP method, endpoint, and required headers for authentication. ```APIDOC ## Get a delivery vehicle (REST) ### Description Retrieves a specific delivery vehicle's data using the REST API. ### Method GET ### Endpoint `https://fleetengine.googleapis.com/v1/providers//deliveryVehicles/` ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the GCP project. - **vehicleId** (string) - Required - The ID of the delivery vehicle. #### Query Parameters None #### Request Body None ### Request Example ```bash # Set JWT, PROJECT_ID, and VEHICLE_ID in the local environment curl -H "Authorization: Bearer ${JWT}" \ "https://fleetengine.googleapis.com/v1/providers/${PROJECT_ID}/deliveryVehicles/${VEHICLE_ID}" ``` ### Response #### Success Response (200) - **vehicle** (object) - The retrieved vehicle entity. ``` -------------------------------- ### Get Task Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/reference/tasks/rest Gets information about a Task. ```APIDOC ## GET /v1/{name=providers/*/tasks/*} ### Description Gets information about a `Task`. ### Method GET ### Endpoint /v1/{name=providers/*/tasks/*} ``` -------------------------------- ### Unavailable init Method Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/reference/ios/Classes/GMTSTimestamp.html The default init method is unavailable. Use -initWithSeconds:nanos: instead. ```objc - (instancetype)init; ``` -------------------------------- ### Example Task Tracking View Configuration Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/scheduled/shipment-tracking/style-map Configure visibility for route polylines, estimated arrival time, and remaining stop count. Use thresholds for proximity and distance, or set to never show. ```json { "taskTrackingViewConfig": { "routePolylinePointsVisibility": { "remainingStopCountThreshold": 3 }, "estimatedArrivalTimeVisibility": { "remainingDrivingDistanceMetersThreshold": 5000 }, "remainingStopCountVisibility": { "never": true } } } ``` -------------------------------- ### Start Following a Trip - Kotlin Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/android/share-journey This Kotlin code snippet shows how to initiate trip following. It covers creating a JourneySharingSession from a TripModel, displaying it on the map, and setting up listeners for trip updates. Make sure the consumer API and controller are properly initialized. ```Kotlin class SampleAppActivity : AppCompatActivity(), ConsumerViewModel.JourneySharingListener { // Class implementation override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Create a TripModel instance to listen for updates to the trip specified by this trip name. val tripName = "tripName" val tripModelManager = consumerApi.getTripModelManager() val tripModel = tripModelManager.getTripModel(tripName) // Create a JourneySharingSession instance based on the TripModel. val session = JourneySharingSession.createInstance(tripModel) // Add the JourneySharingSession instance on the map for updating the UI. consumerController.showSession(session) // Register for trip update events. tripModel.registerTripCallback( object : TripModelCallback() { override fun onTripETAToNextWaypointUpdated( tripInfo: TripInfo, timestampMillis: Long?, ) { // ... } override fun onTripActiveRouteRemainingDistanceUpdated( tripInfo: TripInfo, distanceMeters: Int?, ) { // ... } // ... }) } override fun onDestroy() { super.onDestroy() journeySharingSession?.stop() } } ``` -------------------------------- ### Create Podfile for Consumer SDK Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/ios/setup Create a Podfile in your project directory to specify the Consumer SDK as a dependency. Replace 'YOUR_APPLICATION_TARGET_NAME_HERE' with your application's target name. ```ruby source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingConsumer' end ``` -------------------------------- ### Get Remaining Vehicle Stops with GMTDDeliveryVehicleReporter Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/scheduled/reference/ios/Classes/GMTDDeliveryVehicleReporter.html Gets the remaining GMTDVehicleStop objects that the vehicle still needs to visit. ```Swift func remainingVehicleStops() async throws -> [GMTDVehicleStop] ``` ```Objective-C - (void)getRemainingVehicleStopsWithCompletion: (nonnull GMTDVehicleReporterStopCompletionHandler)completion; ``` -------------------------------- ### Initialize ConsumerGoogleMap and ConsumerController in Java Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/android/create-ui Use this Java code to asynchronously get `ConsumerGoogleMap` and `ConsumerController` instances from a `ConsumerMapView`. Ensure `ConsumerMapReadyCallback` is implemented. ```Java private ConsumerGoogleMap consumerGoogleMap; private ConsumerController consumerController; private ConsumerMapView consumerMapView; consumerMapView.getConsumerGoogleMapAsync( new ConsumerMapReadyCallback() { @Override public void onConsumerMapReady(@NonNull ConsumerGoogleMap consumerMap) { consumerGoogleMap = consumerMap; consumerController = consumerMap.getConsumerController(); } }, this, null); ``` -------------------------------- ### -init Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/reference/ios/Classes/GMTDRidesharingDriverAPI.html Unavailable initializer. Use initWithDriverContext: instead. ```APIDOC ## -init ### Description Unavailable. Use `initWithDriverContext:` instead. ### Declaration Objective-C ``` - (null_unspecified instancetype)init; ``` ``` -------------------------------- ### Link Required Frameworks and Libraries Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/ios/minimum-requirements Ensure these frameworks and libraries are linked in your application's target under the 'Build Phases' > 'Link Binary with Libraries' section for manual installation. ```bash Accelerate.framework AudioToolbox.framework AVFoundation.framework CoreData.framework CoreGraphics.framework CoreLocation.framework CoreTelephony.framework CoreText.framework GLKit.framework ImageIO.framework libc++.tbd libxml2.tbd libz.tbd LocalAuthentication.framework OpenGLES.framework QuartzCore.framework SystemConfiguration.framework UIKit.framework WebKit.framework ``` -------------------------------- ### Start Following a Trip - Java Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/android/share-journey Use this Java code to create and display a JourneySharingSession. It demonstrates how to initialize the session with a TripModel, add it to the map, and register for trip update callbacks. Ensure you have the necessary consumer API and controller instances. ```Java public class MainActivity extends AppCompatActivity implements ConsumerViewModel.JourneySharingListener { // Class implementation @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a TripModel instance to listen for updates to the trip specified by this trip name. String tripName = ...; TripModelManager tripModelManager = consumerApi.getTripModelManager(); TripModel tripModel = tripModelManager.getTripModel(tripName); // Create a JourneySharingSession instance based on the TripModel. JourneySharingSession session = JourneySharingSession.createInstance(tripModel); // Add the JourneySharingSession instance on the map for updating the UI. consumerController.showSession(session); // Register for trip update events. tripModel.registerTripCallback(new TripModelCallback() { @Override public void onTripETAToNextWaypointUpdated( TripInfo tripInfo, @Nullable Long timestampMillis) { // ... } @Override public void onTripActiveRouteRemainingDistanceUpdated( TripInfo tripInfo, @Nullable Integer distanceMeters) { // ... } // ... }); } @Override protected void onDestroy() { super.onDestroy(); if (journeySharingSession != null) { journeySharingSession.stop(); } } } ``` -------------------------------- ### -init Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/reference/ios/Classes/GMTSRequest.html The default init method is unavailable and should not be used. Use -initWithRequestHeader: instead. ```APIDOC ## -init Unavailable Use `-initWithRequestHeader:` instead. ### Declaration Objective-C ```objective-c - (nonnull instancetype)init; ``` ``` -------------------------------- ### ListVehicles REST Example Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-list-vehicle This REST example demonstrates how to use the `ListVehicles` method to filter vehicles by type (AUTO) and a custom attribute ('class' set to 'LUXURY'). ```APIDOC ## ListVehicles REST Example ### Description This example filters on both the `vehicle_type` and `attributes` fields using the `filter` string, showing only vehicles of type AUTO and obtaining the LUXURY value for the custom attribute of `class`. You can use the gRPC client libraries or REST. ### Method `POST` ### Endpoint `https://fleetengine.googleapis.com/v1/providers/{project_id}/vehicles:list` ### Parameters #### Request Body - **vehicleTypes** (object) - Optional - A list of vehicle types to filter vehicles by. Example: `{"category": "AUTO"}`. - **filter** (string) - Optional - A filter string to apply to the query. Example: `attributes.class=\"LUXURY\"`. ### Request Example ```bash curl -X POST \ "https://fleetengine.googleapis.com/v1/providers/project-id/vehicles:list" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ --data-binary @- << EOM { "vehicleTypes": [{"category": "AUTO"}], "filter": "attributes.class=\"LUXURY\"", } EOM ``` ### Response #### Success Response (200) - **vehicles** (List) - A list of vehicles matching the query. - **nextPageToken** (string) - A token to retrieve the next page of results. #### Response Example (Response structure not provided in source) ``` -------------------------------- ### Initialize SDK with Access Token Provider Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/reference/ios/Classes/GMTCServices Initialize the SDK by providing an access token provider and a Google Cloud Project ID. This method must be called before any other SDK methods. ```Swift class func setAccessTokenProvider(_ accessTokenProvider: any GMTCAuthorization, providerID: String) ``` ```Objective-C + (void)setAccessTokenProvider: (nonnull id)accessTokenProvider providerID:(nonnull NSString *)providerID; ``` -------------------------------- ### Install Fleet Engine package with npm Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/client-libraries-trips Install the Fleet Engine client library for Node.js or TypeScript using npm. This command adds the necessary package to your project. ```bash npm install @googlemaps/fleetengine ``` -------------------------------- ### Get and Set Trip Request Header Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/reference/ios/Classes/GMTCMutableTripModelOptions.html Set or get the request header that will be appended to each trip info polling call. This allows for custom headers to be sent with each request. ```Swift @NSCopying var tripRequestHeader: GMTSRequestHeader? { get set } ``` ```Objective-C @property (nonatomic, copy, nullable) GMTSRequestHeader *tripRequestHeader; ``` -------------------------------- ### Link Binary with Libraries Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/scheduled/ios/minimum-requirements Add these frameworks and libraries in Xcode's 'Build Phases' under 'Link Binary with Libraries' for manual installation. ```bash `Accelerate.framework` ``` ```bash `AudioToolbox.framework` ``` ```bash `AVFoundation.framework` ``` ```bash `CoreData.framework` ``` ```bash `CoreGraphics.framework` ``` ```bash `CoreLocation.framework` ``` ```bash `CoreTelephony.framework` ``` ```bash `CoreText.framework` ``` ```bash `GLKit.framework` ``` ```bash `ImageIO.framework` ``` ```bash `libc++.tbd` ``` ```bash `libxml2.tbd` ``` ```bash `libz.tbd` ``` ```bash `LocalAuthentication.framework` ``` ```bash `OpenGLES.framework` ``` ```bash `QuartzCore.framework` ``` ```bash `SystemConfiguration.framework` ``` ```bash `UIKit.framework` ``` ```bash `WebKit.framework` ``` -------------------------------- ### Navigate to Project Directory Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/ios/versions Open a terminal and navigate to the directory containing your Podfile before running maintenance commands. ```bash cd ``` -------------------------------- ### Error Details Example Source: https://developers.google.com/maps/documentation/mobility/operations/cloud-logging/reference/tasks/rest/Shared.Types/ErrorResponseLog The 'details' field can contain arbitrary data with a '@type' field identifying the data's format. This example shows an ID with a standard type URI. ```json { "id": 1234, "@type": "types.example.com/standard/id" } ``` -------------------------------- ### Create Vehicle using Java gRPC Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-create-vehicle Example demonstrating how to create a vehicle using the Java gRPC client library for the Fleet Engine API. This includes setting initial vehicle state, capacity, trip types, and attributes. ```APIDOC ## Create Vehicle using Java gRPC ### Description This example shows how to instantiate and use the `VehicleServiceBlockingStub` to create a new vehicle with specified properties like state, capacity, and supported trip types. ### Method `createVehicle` ### Parameters - `parent` (string): The parent resource name, typically in the format `providers/{project_id}`. - `vehicleId` (string): The unique identifier for the vehicle. - `vehicle` (Vehicle object): An object containing the vehicle's configuration, including `vehicleState`, `supportedTripTypes`, `maximumCapacity`, `vehicleType`, and `attributes`. ### Request Example ```java static final String PROJECT_ID = "project-id"; VehicleServiceBlockingStub vehicleService = VehicleService.newBlockingStub(channel); String parent = "providers/" + PROJECT_ID; Vehicle vehicle = Vehicle.newBuilder() .setVehicleState(VehicleState.OFFLINE) // Initial state .addSupportedTripTypes(TripType.EXCLUSIVE) .setMaximumCapacity(4) .setVehicleType(VehicleType.newBuilder().setCategory(VehicleType.Category.AUTO)) .addAttributes(VehicleAttribute.newBuilder() .setKey("on_trip").setValue("false")) // Opaque to the Fleet Engine // Add .setBackToBackEnabled(true) to make this vehicle eligible for trip // matching while even if it is on a trip. By default this is disabled. .build(); CreateVehicleRequest createVehicleRequest = CreateVehicleRequest.newBuilder() .setParent(parent) .setVehicleId("vid-8241890") // Vehicle ID assigned by Rideshare or Delivery Provider .setVehicle(vehicle) // Initial state .build(); try { Vehicle createdVehicle = vehicleService.createVehicle(createVehicleRequest); } catch (StatusRuntimeException e) { // Handle exceptions like ALREADY_EXISTS or PERMISSION_DENIED return; } ``` ### Response #### Success Response (200) - `Vehicle` (object): The created `Vehicle` entity. ``` -------------------------------- ### Create Podfile with Alpha/Beta Pods Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/ios/minimum-requirements Include Alpha and Beta pods for the Driver SDK by specifying alternative source repositories in your Podfile. ```ruby source "https://cpdc-eap.googlesource.com/ridesharing-driver-sdk.git" source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingDriver' end ``` -------------------------------- ### JWT example for fleet operations Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt An example JWT for fleet operations, used to track all tasks and vehicles within a fleet. This token grants broader access for fleet-wide monitoring. ```json { "alg": "RS256", "typ": "JWT", "kid": "YOUR_PRIVATE_KEY_ID" } { "iat": 1516239022, "exp": 1516242622, "aud": "https://oauth2.googleapis.com/token", "iss": "YOUR_SERVICE_ACCOUNT_EMAIL", "sub": "YOUR_SERVICE_ACCOUNT_EMAIL", "email": "YOUR_SERVICE_ACCOUNT_EMAIL", "scope": "https://www.googleapis.com/auth/cloud-platform", "googleapis.com/google_app_engine": { "service": "s~YOUR_PROJECT_ID" }, "client_version": "fleet-engine-samples/java/1.0" } ``` -------------------------------- ### GMTDDeliveryDriverAPI Initializers Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/scheduled/reference/ios/Classes/GMTDDeliveryDriverAPI.html Initialize the API with driver context. ```APIDOC ## GMTDDeliveryDriverAPI Initialization ### `-initWithDriverContext:` Initializes the API. After initialization, driver APIs from different verticals should not be used until this instance has been deallocated. Using driver API instances from multiple verticals in the same SDK session can lead to unexpected behavior. #### Declaration (Swift): ```swift init?(driverContext: GMTDDriverContext) ``` #### Declaration (Objective-C): ```objectivec - (nullable instancetype)initWithDriverContext: (nonnull GMTDDriverContext *)driverContext; ``` #### Parameters: - `_driverContext_` (GMTDDriverContext): An object containing the necessary information for initialization. #### Return Value: An instance of the API. ### `-init` Unavailable. Use `-initWithDriverContext:` instead. #### Declaration (Objective-C): ```objectivec - (null_unspecified instancetype)init; ``` ``` -------------------------------- ### Navigate to Podfile Directory Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/ios/minimum-requirements Change your current directory to the folder containing the Podfile before running pod install. ```bash cd ``` -------------------------------- ### Update Vehicle Fields Example (gRPC) Source: https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-vehicle-fields This example demonstrates how to update vehicle fields, including enabling back-to-back trips and specifying custom attributes, using the gRPC client library. ```APIDOC ## UpdateVehicleRequest (gRPC) ### Description Updates a vehicle's attributes and other fields. This method requires the `update_mask` to be set, indicating which fields to modify. Note that when updating `attributes`, all desired attributes must be included, as unspecified attributes will be removed. ### Method gRPC ### Endpoint `VehicleServiceBlockingStub.updateVehicle` ### Parameters #### Request Body - **name** (string) - Required - The name of the vehicle to update, in the format `providers/{provider_id}/vehicles/{vehicle_id}`. - **vehicle** (Vehicle) - Required - The `Vehicle` object containing the updated fields. - **update_mask** (FieldMask) - Required - A field mask that specifies which vehicle fields to update. Example paths: `vehicle_state`, `attributes`, `back_to_back_enabled`. ### Request Example ```java static final String PROJECT_ID = "project-id"; static final String VEHICLE_ID = "vid-8241890"; VehicleServiceBlockingStub vehicleService = VehicleService.newBlockingStub(channel); String vehicleName = "providers/" + PROJECT_ID + "/vehicles/" + VEHICLE_ID; Vehicle updatedVehicle = Vehicle.newBuilder() .setVehicleState(VehicleState.ONLINE) .addAllAttributes(ImmutableList.of( VehicleAttribute.newBuilder().setKey("class").setValue("ECONOMY").build(), VehicleAttribute.newBuilder().setKey("cash_only").setValue("false").build())) .setBackToBackEnabled(true) .build(); UpdateVehicleRequest updateVehicleRequest = UpdateVehicleRequest.newBuilder() .setName(vehicleName) .setVehicle(updatedVehicle) .setUpdateMask(FieldMask.newBuilder() .addPaths("vehicle_state") .addPaths("attributes") .addPaths("back_to_back_enabled")) .build(); try { Vehicle updatedVehicle = vehicleService.updateVehicle(updateVehicleRequest); } catch (StatusRuntimeException e) { // Handle exceptions } ``` ### Response #### Success Response (200) - **Vehicle** (Vehicle) - The updated vehicle object. #### Response Example (Vehicle object structure) ``` -------------------------------- ### -initWithDriverContext: Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/reference/ios/Classes/GMTDRidesharingDriverAPI.html Initializes the API with the necessary driver context. After initialization, driver APIs from different verticals should not be used until this instance has been deallocated. ```APIDOC ## -initWithDriverContext: ### Description Initializes the API. After initialization, driver APIs from different verticals should not be used until this instance has been deallocated. Using driver API instances from multiple verticals in the same SDK session can lead to unexpected behavior. ### Declaration Swift ``` init?(driverContext: GMTDDriverContext) ``` Objective-C ``` - (nullable instancetype)initWithDriverContext: (nonnull GMTDDriverContext *)driverContext; ``` ### Parameters - `_driverContext_` (GMTDDriverContext) - An object containing the necessary information for initialization. ### Return Value An instance of the API. ``` -------------------------------- ### Provide API Key in Objective-C Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/scheduled/ios/configure-project Call [GMSServices provideAPIKey:] with your API key within the application:didFinishLaunchingWithOptions: method in your AppDelegate.m file. ```objectivec [GMSServices provideAPIKey:@"YOUR_API_KEY"]; ``` -------------------------------- ### Get and Set Auto Refresh Time Interval Source: https://developers.google.com/maps/documentation/mobility/journey-sharing/on-demand/reference/ios/Classes/GMTCMutableTripModelOptions.html Set or get the time interval for refreshing trip information from the server. This property controls how often the client polls for updated trip status. ```Swift var autoRefreshTimeInterval: TimeInterval { get set } ``` ```Objective-C @property (nonatomic) NSTimeInterval autoRefreshTimeInterval; ``` -------------------------------- ### -init Source: https://developers.google.com/maps/documentation/mobility/driver-sdk/on-demand/reference/ios/Classes/GMTDDriverAPI.html Unavailable. This abstract superclass cannot be directly instantiated. ```APIDOC ## -init ### Description Unavailable This abstract superclass cannot be directly instantiated. ### Declaration Objective-C ```objectivec - (null_unspecified instancetype)init; ``` ```