Créer et afficher un trajet à destination unique

Ce tutoriel vous explique comment créer un trajet avec une seule prise en charge et dépose, puis comment partager ce parcours avec un consommateur.

Prérequis

Pour suivre ce tutoriel, veillez à:

  1. Configurer Fleet Engine Pour en savoir plus, consultez Fleet Engine: configuration initiale.

  2. Intégrer votre application au SDK Driver Pour en savoir plus, consultez la page Initialiser le SDK Driver pour Android et le guide d'intégration du SDK Driver pour iOS.

  3. Intégrez votre application destinée au grand public avec le SDK grand public. Pour en savoir plus, consultez les pages Premiers pas avec le SDK client pour Android et Premiers pas avec le SDK client pour iOS.

  4. Configurer des jetons d'autorisation Pour en savoir plus sur les jetons d'autorisation, consultez la section Créer un jeton Web JSON pour l'autorisation dans le guide "Premiers pas avec Fleet Engine", et la section Authentification et autorisation dans la documentation du SDK client pour Fleet Engine.

Étape 1. Créer un véhicule dans Fleet Engine

Les véhicules sont des objets qui représentent les véhicules de votre parc. Vous devez les créer dans Fleet Engine pour pouvoir les suivre dans l'application grand public.

Vous pouvez créer un véhicule en utilisant l'une des deux approches suivantes:

gRPC
Appelez la méthode CreateVehicle() avec le message de requête CreateVehicleRequest. Vous devez disposer des droits de super-utilisateur Fleet Engine pour appeler CreateVehicle().
REST
Appelez le https://fleetengine.googleapis.com/v1/providers.vehicles.create.

Mises en garde

Les mises en garde suivantes s'appliquent lorsque vous créez un véhicule.

  • Veillez à définir l'état initial du véhicule sur OFFLINE. Fleet Engine peut ainsi détecter votre véhicule pour la correspondance de trajets.

  • Le champ provider_id du véhicule doit être identique à l'ID du projet Google Cloud contenant les comptes de service utilisés pour appeler Fleet Engine. Bien que plusieurs comptes de service puissent accéder à Fleet Engine pour le même fournisseur de covoiturage, Fleet Engine n'est actuellement pas compatible avec les comptes de service de différents projets Google Cloud accédant aux mêmes véhicules.

  • La réponse renvoyée par CreateVehicle() contient l'instance Vehicle. L'instance est supprimée au bout de sept jours si elle n'a pas été mise à jour à l'aide de UpdateVehicle(). Vous devez appeler GetVehicle() avant d'appeler CreateVehicle() pour vérifier que le véhicule n'existe pas déjà. Si GetVehicle() renvoie une erreur NOT_FOUND, vous devez appeler CreateVehicle(). Pour en savoir plus, consultez Véhicules et leur cycle de vie.

Exemple

L'exemple de code de fournisseur suivant montre comment créer un véhicule dans Fleet Engine.

static final String PROJECT_ID = "my-rideshare-co-gcp-project";

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))
    .build();

CreateVehicleRequest createVehicleRequest = CreateVehicleRequest.newBuilder()
    .setParent(parent)
    .setVehicleId("8241890")  // Vehicle ID assigned by solution provider.
    .setVehicle(vehicle)      // Initial state.
    .build();

// The Vehicle is created in the OFFLINE state, and no initial position is
// provided.  When the driver app calls the rideshare provider, the state can be
// set to ONLINE, and the driver app updates the vehicle location.
try {
  Vehicle createdVehicle = vehicleService.createVehicle(createVehicleRequest);
} catch (StatusRuntimeException e) {
  Status s = e.getStatus();
  switch (s.getCode()) {
    case ALREADY_EXISTS:
      break;
    case PERMISSION_DENIED:
      break;
  }
  return;
}

Étape 2. Activer le suivi de la position

Le suivi de la position consiste à suivre la position du véhicule pendant le trajet. L'application de conduite envoie des données de télémétrie à Fleet Engine, qui contient la position actuelle du véhicule. Ce flux d'informations de position constamment mis à jour permet de transmettre la progression du véhicule sur le trajet. Lorsque vous activez le suivi de la position, l'application de conduite commence à envoyer ces données de télémétrie, à une fréquence par défaut d'une fois toutes les cinq secondes.

Pour activer le suivi de la position sur Android et iOS, procédez comme suit:

Exemple

L'exemple de code suivant montre comment activer le suivi de la position.

Java

RidesharingVehicleReporter vehicleReporter = ...;

vehicleReporter.enableLocationTracking();

Kotlin

val vehicleReporter = ...

vehicleReporter.enableLocationTracking()

Swift

vehicleReporter.locationTrackingEnabled = true

Objective-C

_vehicleReporter.locationTrackingEnabled = YES;

Étape 3. Définir l'état du véhicule sur "En ligne"

Vous mettez un véhicule en service (pour le rendre disponible à l'utilisation) en définissant son état sur online, mais vous ne pouvez pas le faire avant d'avoir activé le suivi de la position.

Pour définir l'état du véhicule sur "En ligne" pour Android et iOS, procédez comme suit:

Exemple

L'exemple de code suivant montre comment définir l'état du véhicule sur ONLINE.

Java

vehicleReporter.setVehicleState(VehicleState.ONLINE);

Kotlin

vehicleReporter.setVehicleState(VehicleState.ONLINE)

Swift

vehicleReporter.update(.online)

Objective-C

[_vehicleReporter updateVehicleState:GMTDVehicleStateOnline];

Étape 4. Créer un trajet dans Fleet Engine

En programmation, un Trip est un objet qui représente un trajet. Vous devez en créer un pour chaque requête de trajet afin qu'elles puissent être mises en correspondance avec des véhicules, puis suivies.

Attributs obligatoires

Les champs suivants sont obligatoires pour créer un trajet.

parent
Chaîne comprenant l'ID du fournisseur. Il doit être identique à l'ID du projet Google Cloud contenant les comptes de service utilisés pour appeler Fleet Engine.
trip_id
Chaîne que vous créez qui identifie de manière unique ce trajet.
trip_type
L'une des valeurs d'énumération TripType (SHARED ou EXCLUSIVE).
pickup_point
Point de départ du trajet.

Lorsque vous créez un trajet, vous pouvez renseigner les champs number_of_passengers, dropoff_point et vehicle_id, bien que ces champs ne soient pas obligatoires. Lorsque vous fournissez un vehicle_id, le trajet contient une liste des points de cheminement restants, que vous pouvez utiliser pour définir la destination dans l'application du conducteur.

Exemple

L'exemple suivant montre comment créer un voyage à destination du centre commercial Grand Indonesia East Mall. Le trajet implique deux passagers, il est exclusif et son état est nouveau. Le provider_id du trajet doit être identique à l'ID du projet. Dans l'exemple, le fournisseur de services de covoiturage a créé le projet Google Cloud avec l'ID de projet my-rideshare-co-gcp-project. Ce projet doit inclure un compte de service pour appeler Fleet Engine.

static final String PROJECT_ID = "my-rideshare-co-gcp-project";

TripServiceBlockingStub tripService = TripService.newBlockingStub(channel);

// Trip initial settings.
String parent = "providers/" + PROJECT_ID;

Trip trip = Trip.newBuilder()
    .setTripType(TripType.EXCLUSIVE) // Use TripType.SHARED for carpooling.
    .setPickupPoint(                 // Grand Indonesia East Mall.
        TerminalLocation.newBuilder().setPoint(
            LatLng.newBuilder()
                .setLatitude(-6.195139).setLongitude(106.820826)))
    .setNumberOfPassengers(2)
    // Provide the drop-off point if available.
    .setDropoffPoint(
        TerminalLocation.newBuilder().setPoint(
            LatLng.newBuilder()
                .setLatitude(-6.1275).setLongitude(106.6537)))
    .build();

// Create trip request
CreateTripRequest createTripRequest = CreateTripRequest.newBuilder()
    .setParent(parent)
    .setTripId("trip-8241890")  // Trip ID assigned by the provider.
    .setTrip(trip)              // The initial state is NEW.
    .build();

// Error handling.
try {
  Trip createdTrip = tripService.createTrip(createTripRequest);
} catch (StatusRuntimeException e) {
  Status s = e.getStatus();
  switch (s.getCode()) {
    case ALREADY_EXISTS:
      break;
    case PERMISSION_DENIED:
      break;
  }
  return;
}

Étape 5 : Définir la destination dans l'application du conducteur

Après avoir associé un consommateur à un conducteur, vous devez configurer la destination du trajet dans l'application du conducteur. Vous pouvez récupérer la destination du véhicule à partir de la collection de points de cheminement, qui est renvoyée par GetTrip(), UpdateTrip() et GetVehicle().

Pour que l'application consommateur puisse afficher correctement le trajet, les coordonnées géographiques (LatLng) fournies à setDestination() doivent correspondre à celles du point de cheminement du trajet. Pour en savoir plus, consultez les tutoriels Router vers une destination unique et Router vers plusieurs destinations.

Exemple

L'exemple de code suivant montre comment définir la destination dans l'application du pilote.

Java

private void navigateToPlace(String placeId, RoutingOptions travelMode) {
  Waypoint destination;
  try {
    destination = Waypoint.fromPlaceId(placeId, null);
  } catch (Waypoint.UnsupportedPlaceIdException e) {
    displayMessage("Error starting navigation: Place ID is not supported.");
    return;
  }

  // Create a future to await the result of the asynchronous navigator task.
  ListenableResultFuture<Navigator.RouteStatus> pendingRoute =
      mNavigator.setDestination(destination, travelMode);

  // Define the action to perform when the SDK has determined the route.
  pendingRoute.setOnResultListener(
      new ListenableResultFuture.OnResultListener<Navigator.RouteStatus>() {
        @Override
        public void onResult(Navigator.RouteStatus code) {
          switch (code) {
            case OK:
              // Hide the toolbar to maximize the navigation UI.
              if (getActionBar() != null) {
                getActionBar().hide();
              }

              // Enable voice audio guidance (through the device speaker).
              mNavigator.setAudioGuidance(
                  Navigator.AudioGuidance.VOICE_ALERTS_AND_GUIDANCE);

              // Simulate vehicle progress along the route for demo/debug builds.
              if (BuildConfig.DEBUG) {
                mNavigator.getSimulator().simulateLocationsAlongExistingRoute(
                    new SimulationOptions().speedMultiplier(5));
              }

              // Start turn-by-turn guidance along the current route.
              mNavigator.startGuidance();
              break;
            // Handle error conditions returned by the navigator.
            case NO_ROUTE_FOUND:
              displayMessage("Error starting navigation: No route found.");
              break;
            case NETWORK_ERROR:
              displayMessage("Error starting navigation: Network error.");
              break;
            case ROUTE_CANCELED:
              displayMessage("Error starting navigation: Route canceled.");
              break;
            default:
              displayMessage("Error starting navigation: "
                  + String.valueOf(code));
          }
        }
      });
}

Kotlin

private fun navigateToPlace(placeId: String, travelMode: RoutingOptions) {
  val destination =
    try {
      Waypoint.fromPlaceId(placeId, null)
    } catch (e: Waypoint.UnsupportedPlaceIdException) {
      displayMessage("Error starting navigation: Place ID is not supported.")
      return@navigateToPlace
    }

  // Create a future to await the result of the asynchronous navigator task.
  val pendingRoute = mNavigator.setDestination(destination, travelMode)

  // Define the action to perform when the SDK has determined the route.
  pendingRoute.setOnResultListener(
    object : ListenableResultFuture.OnResultListener<Navigator.RouteStatus>() {
      override fun onResult(code: Navigator.RouteStatus) {
        when (code) {
          Navigator.RouteStatus.OK -> {
            // Hide the toolbar to maximize the navigation UI.
            getActionBar()?.hide()

            // Enable voice audio guidance (through the device speaker).
            mNavigator.setAudioGuidance(Navigator.AudioGuidance.VOICE_ALERTS_AND_GUIDANCE)

            // Simulate vehicle progress along the route for demo/debug builds.
            if (BuildConfig.DEBUG) {
              mNavigator
                .getSimulator()
                .simulateLocationsAlongExistingRoute(SimulationOptions().speedMultiplier(5))
            }

            // Start turn-by-turn guidance along the current route.
            mNavigator.startGuidance()
          }
          Navigator.RouteStatus.NO_ROUTE_FOUND -> {
            displayMessage("Error starting navigation: No route found.")
          }
          Navigator.RouteStatus.NETWORK_ERROR -> {
            displayMessage("Error starting navigation: Network error.")
          }
          Navigator.RouteStatus.ROUTE_CANCELED -> {
            displayMessage("Error starting navigation: Route canceled.")
          }
          else -> {
            displayMessage("Error starting navigation: ${code.name}")
          }
        }
      }
    }
  )
}

Swift

private func startNavigation() {
  let destinations = [
    GMSNavigationWaypoint(
      placeID: "ChIJnUYTpNASkFQR_gSty5kyoUk", title: "PCC Natural Market"),
    GMSNavigationWaypoint(
      placeID: "ChIJJ326ROcSkFQRBfUzOL2DSbo", title: "Marina Park"),
  ]

  mapView.navigator?.setDestinations(destinations, callback: { routeStatus in
    guard routeStatus == .OK else {
      // Error starting navigation.
      return
    }
    mapView.locationSimulator?.simulateLocationsAlongExistingRoute()
    mapView.navigator?.isGuidanceActive = true
    mapView.navigator?.sendsBackgroundNotifications = true
    mapView.cameraMode = .following
  })
}

Objective-C

- (void)startNavigation {
  NSArray<GMSNavigationWaypoint *> *destinations =
  @[[[GMSNavigationWaypoint alloc] initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"
                                             title:@"PCC Natural Market"],
    [[GMSNavigationWaypoint alloc] initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"
                                             title:@"Marina Park"]];

  [_mapView.navigator setDestinations:destinations
                             callback:^(GMSRouteStatus routeStatus) {
                               if (routeStatus != GMSRouteStatusOK) {
                                 // Error starting navigation.
                                 return;
                               }
                               [_mapView.locationSimulator simulateLocationsAlongExistingRoute];
                               _mapView.navigator.guidanceActive = YES;
                               _mapView.navigator.sendsBackgroundNotifications = YES;
                               _mapView.cameraMode = GMSNavigationCameraModeFollowing;
                             }];
}

Étape 6 : Écouter les informations sur les trajets dans l'application grand public

  • Pour Android, vous pouvez écouter les mises à jour de données d'un trajet en obtenant un objet TripModel à partir de TripModelManager et en enregistrant un écouteur TripModelCallback.

  • Pour iOS, vous pouvez écouter les mises à jour de données d'un trajet en obtenant un objet GMTCTripModel à partir de GMTCTripService et en enregistrant un abonné GMTCTripModelSubscriber.

Un écouteur TripModelCallback et un abonné GMTCTripModelSubscriber permettent à votre application de recevoir des mises à jour périodiques de la progression du trajet à chaque actualisation en fonction de l'intervalle d'actualisation automatique. Seules les valeurs modifiées peuvent déclencher le rappel. Sinon, le rappel reste silencieux.

Les méthodes TripModelCallback.onTripUpdated() et tripModel(_:didUpdate:updatedPropertyFields:) sont toujours appelées, quelles que soient les modifications de données.

Exemple 1

L'exemple de code suivant montre comment obtenir un TripModel à partir de TripModelManager/GMTCTripService et définir un écouteur sur celui-ci.

Java

// Start journey sharing after a trip has been created via Fleet Engine.
TripModelManager tripModelManager = consumerApi.getTripModelManager();

// Get a TripModel object.
TripModel tripModel = tripModelManager.getTripModel(tripName);

// Register a listener on the trip.
TripModelCallback tripCallback = new TripModelCallback() {
  ...
};
tripModel.registerTripCallback(tripCallback);

// Set the refresh interval.
TripModelOptions tripModelOptions = TripModelOptions.builder()
    .setRefreshInterval(5000) // interval in milliseconds, so 5 seconds
    .build();
tripModel.setTripModelOptions(tripModelOptions);

// The trip stops auto-refreshing when all listeners are unregistered.
tripModel.unregisterTripCallback(tripCallback);

Kotlin

// Start journey sharing after a trip has been created via Fleet Engine.
val tripModelManager = consumerApi.getTripModelManager()

// Get a TripModel object.
val tripModel = tripModelManager.getTripModel(tripName)

// Register a listener on the trip.
val tripCallback = TripModelCallback() {
  ...
}

tripModel.registerTripCallback(tripCallback)

// Set the refresh interval.
val tripModelOptions =
  TripModelOptions.builder()
    .setRefreshInterval(5000) // interval in milliseconds, so 5 seconds
    .build()

tripModel.setTripModelOptions(tripModelOptions)

// The trip stops auto-refreshing when all listeners are unregistered.
tripModel.unregisterTripCallback(tripCallback)

Swift

let tripService = GMTCServices.shared().tripService

// Create a tripModel instance for listening for updates from the trip
// specified by the trip name.
let tripModel = tripService.tripModel(forTripName: tripName)

// Register for the trip update events.
tripModel.register(self)

// Set the refresh interval (in seconds).
tripModel.options.autoRefreshTimeInterval = 5

// Unregister for the trip update events.
tripModel.unregisterSubscriber(self)

Objective-C

GMTCTripService *tripService = [GMTCServices sharedServices].tripService;

// Create a tripModel instance for listening for updates from the trip
// specified by the trip name.
GMTCTripModel *tripModel = [tripService tripModelForTripName:tripName];

// Register for the trip update events.
[tripModel registerSubscriber:self];

// Set the refresh interval (in seconds).
tripModel.options.autoRefreshTimeInterval = 5;

// Unregister for the trip update events.
[tripModel unregisterSubscriber:self];

Exemple 2

L'exemple de code suivant montre comment configurer un écouteur TripModelCallback et un abonné GMTCTripModelSubscriber.

Java

// Implements a callback for the trip model so your app can listen for trip
// updates from Fleet Engine.
TripModelCallback subscriber =
  new TripModelCallback() {

    @Override
    public void onTripStatusUpdated(TripInfo tripInfo, @TripStatus int status) {
      // ...
    }

    @Override
    public void onTripActiveRouteUpdated(TripInfo tripInfo, List<LatLng> route) {
      // ...
    }

    @Override
    public void onTripVehicleLocationUpdated(
        TripInfo tripInfo, @Nullable VehicleLocation vehicleLocation) {
      // ...
    }

    @Override
    public void onTripPickupLocationUpdated(
        TripInfo tripInfo, @Nullable TerminalLocation pickup) {
      // ...
    }

    @Override
    public void onTripPickupTimeUpdated(TripInfo tripInfo, @Nullable Long timestampMillis) {
      // ...
    }

    @Override
    public void onTripDropoffLocationUpdated(
        TripInfo tripInfo, @Nullable TerminalLocation dropoff) {
      // ...
    }

    @Override
    public void onTripDropoffTimeUpdated(TripInfo tripInfo, @Nullable Long timestampMillis) {
      // ...
    }

    @Override
    public void onTripETAToNextWaypointUpdated(
        TripInfo tripInfo, @Nullable Long timestampMillis) {
      // ...
    }

    @Override
    public void onTripActiveRouteRemainingDistanceUpdated(
        TripInfo tripInfo, @Nullable Integer distanceMeters) {
      // ...
    }

    @Override
    public void onTripUpdateError(TripInfo tripInfo, TripUpdateError error) {
      // ...
    }

    @Override
    public void onTripUpdated(TripInfo tripInfo) {
      // ...
    }

    @Override
    public void onTripRemainingWaypointsUpdated(
        TripInfo tripInfo, List<TripWaypoint> waypointList) {
      // ...
    }

    @Override
    public void onTripIntermediateDestinationsUpdated(
        TripInfo tripInfo, List<TerminalLocation> intermediateDestinations) {
      // ...
    }

    @Override
    public void onTripRemainingRouteDistanceUpdated(
        TripInfo tripInfo, @Nullable Integer distanceMeters) {
      // ...
    }

    @Override
    public void onTripRemainingRouteUpdated(TripInfo tripInfo, List<LatLng> route) {
      // ...
    }
  };

Kotlin

// Implements a callback for the trip model so your app can listen for trip
// updates from Fleet Engine.
val subscriber =
  object : TripModelCallback() {
    override fun onTripStatusUpdated(tripInfo: TripInfo, status: @TripStatus Int) {
      // ...
    }

    override fun onTripActiveRouteUpdated(tripInfo: TripInfo, route: List<LatLng>) {
      // ...
    }

    override fun onTripVehicleLocationUpdated(
      tripInfo: TripInfo,
      vehicleLocation: VehicleLocation?
    ) {
      // ...
    }

    override fun onTripPickupLocationUpdated(tripInfo: TripInfo, pickup: TerminalLocation?) {
      // ...
    }

    override fun onTripPickupTimeUpdated(tripInfo: TripInfo, timestampMillis: Long?) {
      // ...
    }

    override fun onTripDropoffLocationUpdated(tripInfo: TripInfo, dropoff: TerminalLocation?) {
      // ...
    }

    override fun onTripDropoffTimeUpdated(tripInfo: TripInfo, timestampMillis: Long?) {
      // ...
    }

    override fun onTripETAToNextWaypointUpdated(tripInfo: TripInfo, timestampMillis: Long?) {
      // ...
    }

    override fun onTripActiveRouteRemainingDistanceUpdated(
      tripInfo: TripInfo,
      distanceMeters: Int?
    ) {
      // ...
    }

    override fun onTripUpdateError(tripInfo: TripInfo, error: TripUpdateError) {
      // ...
    }

    override fun onTripUpdated(tripInfo: TripInfo) {
      // ...
    }

    override fun onTripRemainingWaypointsUpdated(
      tripInfo: TripInfo,
      waypointList: List<TripWaypoint>
    ) {
      // ...
    }

    override fun onTripIntermediateDestinationsUpdated(
      tripInfo: TripInfo,
      intermediateDestinations: List<TerminalLocation>
    ) {
      // ...
    }

    override fun onTripRemainingRouteDistanceUpdated(tripInfo: TripInfo, distanceMeters: Int?) {
      // ...
    }

    override fun onTripRemainingRouteUpdated(tripInfo: TripInfo, route: List<LatLng>) {
      // ...
    }
  }

Swift

class TripModelSubscriber: NSObject, GMTCTripModelSubscriber {

  func tripModel(_: GMTCTripModel, didUpdate trip: GMTSTrip?, updatedPropertyFields: GMTSTripPropertyFields) {
    // Update the UI with the new `trip` data.
    updateUI(with: trip)
    ...
  }

  func tripModel(_: GMTCTripModel, didUpdate tripStatus: GMTSTripStatus) {
    // Handle trip status did change.
  }

  func tripModel(_: GMTCTripModel, didUpdateActiveRoute activeRoute: [GMTSLatLng]?) {
    // Handle trip active route did update.
  }

  func tripModel(_: GMTCTripModel, didUpdate vehicleLocation: GMTSVehicleLocation?) {
    // Handle vehicle location did update.
  }

  func tripModel(_: GMTCTripModel, didUpdatePickupLocation pickupLocation: GMTSTerminalLocation?) {
    // Handle pickup location did update.
  }

  func tripModel(_: GMTCTripModel, didUpdateDropoffLocation dropoffLocation: GMTSTerminalLocation?) {
    // Handle drop off location did update.
  }

  func tripModel(_: GMTCTripModel, didUpdatePickupETA pickupETA: TimeInterval) {
    // Handle the pickup ETA did update.
  }

  func tripModel(_: GMTCTripModel, didUpdateDropoffETA dropoffETA: TimeInterval) {
    // Handle the drop off ETA did update.
  }

  func tripModel(_: GMTCTripModel, didUpdateRemaining remainingWaypoints: [GMTSTripWaypoint]?) {
    // Handle updates to the pickup, dropoff or intermediate destinations of the trip.
  }

  func tripModel(_: GMTCTripModel, didFailUpdateTripWithError error: Error?) {
    // Handle the error.
  }

  func tripModel(_: GMTCTripModel, didUpdateIntermediateDestinations intermediateDestinations: [GMTSTerminalLocation]?) {
    // Handle the intermediate destinations being updated.
  }

  ...
}

Objective-C

@interface TripModelSubscriber : NSObject <GMTCTripModelSubscriber>
@end

@implementation TripModelSubscriber

- (void)tripModel:(GMTCTripModel *)tripModel
            didUpdateTrip:(nullable GMTSTrip *)trip
    updatedPropertyFields:(GMTSTripPropertyFields)updatedPropertyFields {
  // Update the UI with the new `trip` data.
  [self updateUIWithTrip:trip];
  ...
}

- (void)tripModel:(GMTCTripModel *)tripModel didUpdateTripStatus:(enum GMTSTripStatus)tripStatus {
  // Handle trip status did change.
}

- (void)tripModel:(GMTCTripModel *)tripModel
    didUpdateActiveRoute:(nullable NSArray<GMTSLatLng *> *)activeRoute {
  // Handle trip route did update.
}

- (void)tripModel:(GMTCTripModel *)tripModel
    didUpdateVehicleLocation:(nullable GMTSVehicleLocation *)vehicleLocation {
  // Handle vehicle location did update.
}

- (void)tripModel:(GMTCTripModel *)tripModel
    didUpdatePickupLocation:(nullable GMTSTerminalLocation *)pickupLocation {
  // Handle pickup location did update.
}

- (void)tripModel:(GMTCTripModel *)tripModel
    didUpdateDropoffLocation:(nullable GMTSTerminalLocation *)dropoffLocation {
  // Handle drop off location did update.
}

- (void)tripModel:(GMTCTripModel *)tripModel didUpdatePickupETA:(NSTimeInterval)pickupETA {
  // Handle the pickup ETA did update.
}

- (void)tripModel:(GMTCTripModel *)tripModel
    didUpdateRemainingWaypoints:(nullable NSArray<GMTSTripWaypoint *> *)remainingWaypoints {
  // Handle updates to the pickup, dropoff or intermediate destinations of the trip.
}

- (void)tripModel:(GMTCTripModel *)tripModel didUpdateDropoffETA:(NSTimeInterval)dropoffETA {
  // Handle the drop off ETA did update.
}

- (void)tripModel:(GMTCTripModel *)tripModel didFailUpdateTripWithError:(nullable NSError *)error {
  // Handle the error.
}

- (void)tripModel:(GMTCTripModel *)tripModel
    didUpdateIntermediateDestinations:
        (nullable NSArray<GMTSTerminalLocation *> *)intermediateDestinations {
  // Handle the intermediate destinations being updated.
}
…
@end

Pour accéder aux informations relatives au trajet à tout moment, procédez comme suit:

  • Appelez la méthode TripModel.getTripInfo() du SDK client pour Android. L'appel de cette méthode ne force pas l'actualisation des données, même si celles-ci continuent d'être actualisées à la fréquence d'actualisation.

  • Obtenez la propriété du SDK client pour iOS GMTCTripModel.currentTrip.

Étape 7. Modifier le trajet avec l'ID du véhicule

Vous devez configurer le trajet avec un ID de véhicule afin que Fleet Engine puisse suivre le véhicule tout au long de son trajet.

  • Vous pouvez mettre à jour le trajet avec l'ID du véhicule en appelant le point de terminaison UpdateTrip avec un UpdateTripRequest. Utilisez le champ update_mask pour indiquer que vous mettez à jour l'ID du véhicule.

Remarques

  • Si vous ne spécifiez pas de destination lorsque vous créez le trajet, vous pouvez toujours le faire ici.

  • Si vous devez modifier le véhicule lors d'un trajet en cours, vous devez définir l'état du trajet sur "Nouveau", puis mettre à jour le trajet (comme vous l'avez fait ci-dessus) avec le nouvel ID du véhicule.

Exemple

L'exemple de code suivant montre comment mettre à jour le trajet avec un ID de véhicule.

static final String PROJECT_ID = "my-rideshare-co-gcp-project";
static final String TRIP_ID = "trip-8241890";

String tripName = "providers/" + PROJECT_ID + "/trips/" + TRIP_ID;

TripServiceBlockingStub tripService = TripService.newBlockingStub(channel);

// The trip settings to update.
Trip trip = Trip.newBuilder()
    .setVehicleId("8241890")
    .build();

// The trip update request.
UpdateTripRequest updateTripRequest =
    UpdateTripRequest.newBuilder()      // No need for the header.
        .setName(tripName)
        .setTrip(trip)
        .setUpdateMask(FieldMask.newBuilder().addPaths("vehicle_id"))
        .build();

// Error handling.
// If the Fleet Engine has both a trip and vehicle with IDs, and if the
// credentials validate, then the service updates the trip.
try {
  Trip updatedTrip = tripService.updateTrip(updateTripRequest);
} catch (StatusRuntimeException e) {
  Status s = e.getStatus();
  switch (s.getCode()) {
    case NOT_FOUND:                    // Neither the trip nor vehicle exist.
      break;
    case PERMISSION_DENIED:
      break;
  }
  return;
}

Étape 8 : Afficher le parcours dans l'application grand public

Utilisez l'objet ConsumerController pour accéder aux API de l'élément d'interface utilisateur Rides and Deliveries.

Pour en savoir plus, consultez la section Utiliser les API des éléments d'interface utilisateur.

Exemple

L'exemple de code suivant montre comment démarrer l'interface utilisateur de partage de parcours.

Java

JourneySharingSession session = JourneySharingSession.createInstance(tripModel);
consumerController.showSession(session);

Kotlin

val session = JourneySharingSession.createInstance(tripModel)
consumerController.showSession(session)

Swift

let journeySharingSession = GMTCJourneySharingSession(tripModel: tripModel)
mapView.show(journeySharingSession)

Objective-C

GMTCJourneySharingSession *journeySharingSession =
    [[GMTCJourneySharingSession alloc] initWithTripModel:tripModel];
[self.mapView showMapViewSession:journeySharingSession];

Étape 9 : Gérer l'état du trajet dans Fleet Engine

Vous spécifiez l'état d'un trajet à l'aide de l'une des valeurs d'énumération TripStatus. Lorsque l'état d'un trajet change (par exemple, en passant de ENROUTE_TO_PICKUP à ARRIVED_AT_PICKUP), vous devez mettre à jour l'état du trajet via Fleet Engine. L'état du trajet commence toujours par la valeur NEW et se termine par la valeur COMPLETE ou CANCELED. Pour en savoir plus, consultez trip_status.

Exemple

L'exemple de code suivant montre comment mettre à jour l'état du trajet dans Fleet Engine.

static final String PROJECT_ID = "my-rideshare-co-gcp-project";
static final String TRIP_ID = "trip-8241890";

String tripName = "providers/" + PROJECT_ID + "/trips/" + TRIP_ID;

TripServiceBlockingStub tripService = TripService.newBlockingStub(channel);

// Trip settings to be updated.
Trip trip = Trip.newBuilder()
    .setTripStatus(TripStatus.ARRIVED_AT_PICKUP)
    .build();

// Trip update request
UpdateTripRequest updateTripRequest = UpdateTripRequest.newBuilder()
    .setName(tripName)
    .setTrip(trip)
    .setUpdateMask(FieldMask.newBuilder().addPaths("trip_status"))
    .build();

// Error handling.
try {
  Trip updatedTrip = tripService.updateTrip(updateTripRequest);
} catch (StatusRuntimeException e) {
  Status s = e.getStatus();
  switch (s.getCode()) {
    case NOT_FOUND:            // The trip doesn't exist.
      break;
    case FAILED_PRECONDITION:  // The given trip status is invalid.
      break;
    case PERMISSION_DENIED:
      break;
  }
  return;
}