יצירה והצגה של נסיעה ביעד יחיד

במדריך הזה נסביר איך יוצרים נסיעה עם איסוף אחד והורדה אחת, ואיך לשתף את התהליך עם הצרכן.

דרישות מוקדמות

כדי להשלים את המדריך הזה, הקפידו להשלים את השלבים הבאים:

  1. מגדירים את Fleet Engine. מידע נוסף זמין במאמר Fleet Engine: הגדרה ראשונית.

  2. משלבים את האפליקציה עם Driver SDK. מידע נוסף זמין במאמר אתחול ה-SDK של Drive ל-Android ובמאמר מדריך השילוב ל-Driver SDK ל-iOS.

  3. משלבים את האפליקציה שמיועדת לצרכנים עם ה-SDK לצרכנים. למידע נוסף, קראו את המאמר תחילת העבודה עם SDK לצרכנים ל-Android ותחילת העבודה עם SDK לצרכנים ל-iOS.

  4. הגדרת אסימוני הרשאה. מידע נוסף על אסימוני הרשאה זמין במאמר יצירת אסימון אינטרנט מסוג JSON להרשאה במדריך תחילת העבודה עם Fleet Engine, ובמאמר אימות והרשאה במסמכי התיעוד בנושא Consumer SDK עבור Fleet Engine.

שלב 1. יצירת רכב ב-Flet Engine

כלי רכב הם אובייקטים שמייצגים את כלי הרכב שלכם בצי שלכם. עליך ליצור אותם ב-Flet Engine כדי שתהיה לך אפשרות לעקוב אחריהם באפליקציה לצרכן.

אפשר ליצור כלי רכב באחת משתי הגישות הבאות:

gRPC
קוראים לשיטה CreateVehicle() באמצעות הודעת הבקשה של CreateVehicleRequest. כדי לבצע התקשרות אל CreateVehicle(), נדרשות הרשאות משתמש-על של Fleet Engine.
REST
התקשרות אל https://fleetengine.googleapis.com/v1/providers.vehicles.create.

נקודות שצריך לשים לב אליהן:

האזהרות הבאות חלות כשאתם יוצרים רכב.

  • חשוב להגדיר את המצב הראשוני של הרכב כ-OFFLINE. כך אפשר להבטיח ש-Flit Engine יוכל לאתר את הרכב שלך לצורך התאמת נסיעות.

  • ה-provider_id של הרכב צריך להיות זהה למזהה הפרויקט של הפרויקט ב-Google Cloud שמכיל את חשבונות השירות שמשמשים להתקשרות של Fleet Engine. למרות שלמספר חשבונות שירות יש גישה ל-Feet Engine של אותו ספק של שיתוף נסיעה, Fleet Engine לא תומך כרגע בחשבונות שירות מפרויקטים שונים ב-Google Cloud שיש להם גישה לאותם כלי רכב.

  • התשובה שמוחזרת מ-CreateVehicle() מכילה את המופע Vehicle. המכונה נמחקת אחרי שבעה ימים אם היא לא עודכנה באמצעות UpdateVehicle(). כדאי להתקשר למספר GetVehicle() לפני שמתקשרים אל CreateVehicle() רק כדי לוודא שהרכב לא קיים. אם הפקודה GetVehicle() מחזירה שגיאה מסוג NOT_FOUND, צריך להמשיך בקריאה ל-CreateVehicle(). מידע נוסף זמין במאמר כלי רכב ומחזור החיים שלהם.

דוגמה

דוגמת הקוד הבאה של ספק מדגימה איך ליצור רכב ב-Flet 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;
}

שלב 2. הפעלת מעקב אחר מיקום

מעקב אחר מיקומים מתייחס למעקב אחר המיקום של הרכב במהלך הנסיעה, כשאפליקציית הנהג שולחת טלמטריה אל Fleet Engine, שמכיל את המיקום הנוכחי של כלי הרכב. רצף פרטי המיקום, שמתעדכן באופן קבוע, משמש להעברת מידע על התקדמות הרכב במסלול הנסיעה. כשמפעילים מעקב אחר מיקום, אפליקציית הנהג מתחילה לשלוח את נתוני הטלמטריה האלה בתדירות ברירת מחדל של פעם בחמש שניות.

את המעקב אחר מיקום אתם מפעילים עבור Android ו-iOS באופן הבא:

דוגמה

הקוד לדוגמה הבא מדגים איך מפעילים מעקב אחר מיקום.

Java

RidesharingVehicleReporter vehicleReporter = ...;

vehicleReporter.enableLocationTracking();

Kotlin

val vehicleReporter = ...

vehicleReporter.enableLocationTracking()

Swift

vehicleReporter.locationTrackingEnabled = true

Objective-C

_vehicleReporter.locationTrackingEnabled = YES;

שלב 3. הגדרת מצב הרכב למצב אונליין

אתם מביאים רכב לשירות (כלומר, כדי שהוא יהיה זמין לשימוש) על ידי הגדרת המצב שלו לאונליין, אבל לא תוכלו לעשות זאת עד שתפעילו את המעקב אחר המיקום.

אתם מגדירים את מצב הרכב כאונליין ל-Android ול-iOS באופן הבא:

דוגמה

קטע הקוד שבדוגמה הבאה מדגים איך להגדיר את מצב הרכב ONLINE.

Java

vehicleReporter.setVehicleState(VehicleState.ONLINE);

Kotlin

vehicleReporter.setVehicleState(VehicleState.ONLINE)

Swift

vehicleReporter.update(.online)

Objective-C

[_vehicleReporter updateVehicleState:GMTDVehicleStateOnline];

שלב 4. יצירת נסיעה ב-Flet Engine

באופן פרוגרמטי, Trip הוא אובייקט שמייצג מסע, וצריך ליצור אובייקט כזה לכל בקשת נסיעה, כדי שאפשר יהיה להתאים אותם לכלי רכב ולעקוב אחריהם.

מאפיינים נדרשים

השדות הבאים נדרשים כדי ליצור נסיעה.

parent
מחרוזת שכוללת את מזהה הספק. המזהה צריך להיות זהה למזהה הפרויקט של הפרויקט ב-Google Cloud שמכיל את חשבונות השירות שמשמשים להתקשרות של Fleet Engine
trip_id
מחרוזת שאפשר ליצור, שמזהה באופן ייחודי את הנסיעה.
trip_type
אחד מערכי המספור TripType (SHARED או EXCLUSIVE).
pickup_point
נקודת המוצא של הנסיעה.

כשיוצרים נסיעה, אפשר לספק את השדות number_of_passengers, dropoff_point ו-vehicle_id, אבל לא חייבים למלא את השדות האלה. כשמציינים את השדה vehicle_id, הנסיעה מכילה רשימה של ציוני דרך שנותרו, שאפשר להשתמש בה כדי להגדיר את היעד באפליקציית הנהג.

דוגמה

הדוגמה הבאה ממחישה איך ליצור טיול לגרנד אינדונזית במזרח קניון. בנסיעה משתתפים שני נוסעים. היא בלעדית והסטטוס שלה הוא חדש. הערך של provider_id בנסיעה צריך להיות זהה למזהה הפרויקט. בדוגמה, ספק שיתוף הנסיעה יצר את הפרויקט ב-Google Cloud עם מזהה הפרויקט my-rideshare-co-gcp-project. הפרויקט צריך לכלול חשבון שירות לקריאה ל-Flet 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;
}

שלב 5. הגדרת היעד באפליקציית הנהג

אחרי שמתאימים צרכן לנהג, צריך להגדיר את יעד הנסיעה באפליקציית הנהג. אפשר לאחזר את יעד הרכב מאוסף ציוני הדרך שלו, שמוחזר על ידי GetTrip(), UpdateTrip() ו-GetVehicle().

  • הגדרת היעד מתבצעת על ידי קריאה ל-SDK של הניווט עבור שיטת Android setDestination(), או על ידי קריאה ל-Navigation SDK עבור שיטת iOS setDestinations().

כדי שהאפליקציה לצרכן תוכל לעבד את הנסיעה בצורה תקינה, הקואורדינטות הגיאוגרפיות (LatLng) שמצוינות ל-setDestination() חייבות להיות תואמות לאלו שבנקודת המבט. למידע נוסף, אפשר לעיין במדריכים ניתוב ליעד יחיד וניתוב ליעדים מרובים.

דוגמה

דוגמת הקוד הבאה ממחישה איך להגדיר את היעד באפליקציית הנהג.

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;
                             }];
}

שלב 6. אפשר להאזין לעדכוני נסיעות באפליקציה לצרכנים

  • ב-Android, אפשר להאזין לעדכוני נתונים מנסיעה על ידי קבלת אובייקט TripModel מה-TripModelManager ורישום האזנה ל-TripModelCallback.

  • ב-iOS, אפשר להאזין לעדכוני נתונים מנסיעה על ידי קבלת אובייקט GMTCTripModel מ-GMTCTripService ורישום מנוי GMTCTripModelSubscriber.

האזנה ל-TripModelCallback ומנוי GMTCTripModelSubscriber מאפשרים לאפליקציה לקבל עדכונים תקופתיים על התקדמות הנסיעה בכל רענון, בהתאם למרווח הרענון האוטומטי. רק ערכים שמשתנים יכולים להפעיל את הקריאה החוזרת. אחרת, הקריאה החוזרת תישאר שקטה.

המערכת תמיד מפעילה את השיטות TripModelCallback.onTripUpdated() וכן tripModel(_:didUpdate:updatedPropertyFields:), ללא קשר לשינויים בנתונים.

דוגמה 1

דוגמת הקוד הבאה מדגימה איך לקבל TripModel מ-TripModelManager/GMTCTripService ולהגדיר בו listener.

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];

דוגמה 2

דוגמת הקוד הבאה מדגימה איך להגדיר האזנה ל-TripModelCallback ומינוי ל-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

אתם יכולים לגשת למידע על הנסיעה מתי שתרצו באופן הבא:

  • קוראים לפונקציה Consumer SDK for Android TripModel.getTripInfo(). הפעלת השיטה הזו לא מאלצת רענון נתונים, אבל עדיין מתבצע רענון של הנתונים בתדירות הרענון.

  • קבל את ה-SDK לצרכן עבור iOS GMTCTripModel.currentTrip.

שלב 7. מעדכנים את הנסיעה עם מזהה הרכב

עליכם להגדיר את הנסיעה עם מזהה רכב כדי שמנוע Fleet יוכל לעקוב אחרי הרכב לאורך המסלול.

  • אפשר לעדכן את הנסיעה במזהה הרכב על ידי קריאה לנקודת הקצה UpdateTrip באמצעות UpdateTripRequest. השתמשו בשדה update_mask כדי לציין שאתם מעדכנים את מזהה הרכב.

הערות

  • אם לא תציינו יעד בזמן יצירת הנסיעה, תמיד תוכלו לעשות זאת כאן.

  • אם אתם צריכים להחליף את הרכב במהלך נסיעה, עליכם להגדיר את מצב הנסיעה בחזרה למצב חדש, ואז לעדכן את הנסיעה (כפי שעשיתם למעלה) עם מזהה הרכב החדש.

דוגמה

דוגמת הקוד הבאה מדגימה איך לעדכן את הנסיעה באמצעות מזהה רכב.

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;
}

שלב 8. הצגת התהליך באפליקציה לצרכנים

משתמשים באובייקט ConsumerController כדי לגשת לממשקי ה-API של Rides and Deliveries לממשקי המשתמש.

למידע נוסף, תוכלו לקרוא את המאמר שימוש בממשקי API של ממשק המשתמש.

דוגמה

הקוד לדוגמה הבא מדגים איך להתחיל את התהליך של שיתוף ממשק המשתמש.

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];

שלב 9. ניהול מצב הנסיעה ב-Flet Engine

ציון מצב הנסיעה באמצעות אחד מערכי המספור TripStatus. כשמצב הנסיעה משתנה (לדוגמה, משתנה מ-ENROUTE_TO_PICKUP ל-ARRIVED_AT_PICKUP), צריך לעדכן את מצב הנסיעה דרך Fleet Engine. מצב הנסיעה מתחיל תמיד בערך של NEW ומסתיים בערך של COMPLETE או CANCELED. למידע נוסף: trip_status.

דוגמה

דוגמת הקוד הבאה מדגימה איך לעדכן את מצב הנסיעה ב-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;
}