יצירה והצגה של נסיעות מאגר משותף

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

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

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

שלב 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;
}

כדי ליצור Vehicle שתומך בנסיעות במאגר משותף, צריך להוסיף את TripType.SHARED לרשימת סוגי הנסיעות הנתמכים באובייקט Vehicle שמועבר אל CreateVehicleRequest.

Vehicle vehicle = Vehicle.newBuilder()
    .setVehicleState(VehicleState.OFFLINE)
    .addSupportedTripTypes(TripType.SHARED)
    .setMaximumCapacity(4)
    .setVehicleType(VehicleType.newBuilder().setCategory(VehicleType.Category.AUTO))
    .build();

שלב 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, בדיוק כמו שיוצרים נסיעה עם יעד אחד.

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

לספק מאפיינים נדרשים

כדי ליצור נסיעה משותפת במאגר, צריך למלא את השדות הבאים.

parent
מחרוזת שכוללת את מזהה הספק. המזהה צריך להיות זהה למזהה הפרויקט של הפרויקט ב-Google Cloud שמכיל את חשבונות השירות שמשמשים להתקשרות של Fleet Engine
trip_id
מחרוזת שאפשר ליצור, שמזהה באופן ייחודי את הנסיעה.
trip
אובייקט Trip ליצירה.

יש להגדיר את השדות הבאים באובייקט Trip שמועבר אל CreateTripRequest:

trip_type
TripType.SHARED
pickup_point
נקודת המוצא של הנסיעה.
dropoff_point
נקודת ההורדה של הנסיעה. השדה הזה לא נדרש כשיוצרים נסיעה. אפשר להגדיר אותו מאוחר יותר באמצעות UpdateTrip.

דוגמה

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

// Vehicle with VEHICLE_ID ID is already created and it is assigned Trip A.

static final String PROJECT_ID = "my-rideshare-co-gcp-project";
static final String TRIP_ID = "shared-trip-A";
static final String VEHICLE_ID = "your-vehicle-id";
static final String TRIP_A_ID = "trip-a-id";
static final String TRIP_B_ID = "trip-b-id";

TripServiceBlockingStub tripService = TripService.newBlockingStub(channel);

String parent = "providers/" + PROJECT_ID;

LatLng tripBPickup =
    LatLng.newBuilder().setLatitude(-12.12314).setLongitude(88.142123).build();
LatLng tripBDropoff =
    LatLng.newBuilder().setLatitude(-14.12314).setLongitude(90.142123).build();

TerminalLocation tripBPickupTerminalLocation =
    TerminalLocation.newBuilder().setPoint(tripBPickup).build();
TerminalLocation tripBDropoffTerminalLocation =
    TerminalLocation.newBuilder().setPoint(tripBDropoff).build();

// TripA already exists and it's assigned to a vehicle with VEHICLE_ID ID.
Trip tripB = Trip.newBuilder()
    .setTripType(TripType.SHARED)
    .setVehicleId(VEHICLE_ID)
    .setPickupPoint(tripBPickupTerminalLocation)
    .setDropoffPoint(tripBDropoffTerminalLocation)
    .addAllVehicleWaypoints(
        // This is where you define the arrival order for unvisited waypoints.
        // If you don’t specify an order, then the Fleet Engine adds Trip B’s
        // waypoints to the end of Trip A’s.
        ImmutableList.of(
            // Trip B’s pickup point.
            TripWaypoint.newBuilder()
                .setLocation(tripBPickupTerminalLocation)
                .setTripId(TRIP_B_ID)
                .setWaypointType(WaypointType.PICKUP_WAYPOINT_TYPE)
                .build(),
            // Trip A’s drop-off point.
            TripWaypoint.newBuilder()
                .setLocation(tripA.getDropoffPoint())
                .setTripId(TRIP_A_ID)
                .setWaypointType(WaypointType.DROP_OFF_WAYPOINT_TYPE)
                .build(),
            // Trip B’s drop-off point.
            TripWaypoint.newBuilder()
                .setLocation(tripBDropoffTerminalLocation)
                .setTripId(TRIP_B_ID)
                .setWaypointType(WaypointType.DROP_OFF_WAYPOINT_TYPE)
                .build()))
    .build();

// Create Trip request
CreateTripRequest createTripRequest = CreateTripRequest.newBuilder()
    .setParent(parent)
    .setTripId(TRIP_B_ID)
    .setTrip(tripB)
    .build();

try {
  // createdTrip.remainingWaypoints will contain shared-pool waypoints.
  // [tripB.pickup, tripA.dropoff, tripB.dropoff]
  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. מעדכנים את הנסיעה באמצעות מזהה הרכב וציוני הדרך

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

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

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

לדוגמה, יש שתי אפשרויות לנסיעות במאגר משותף: נסיעה א' ונסיעה ב'. נסיעה א' בדרך אל נקודת ההורדה. לאחר מכן מוסיפים את נסיעה B לאותו כלי רכב. באחד UpdateTripRequest של נסיעה ב, מגדירים את vehicleId וגם מגדירים את Trip.vehicle_waypoints לסדר היעד האופטימלי: ב איסוףא הורדהב נשירה.

  • קריאה ל-getVehicle() מחזירה רשימה של ציוני הדרך שנותרו (remainingWaypoints) שמכילה את
    B איסוףהורדהב הורדה.
  • getTrip() או הקריאה החוזרת (callback) onTripRemainingWaypointsUpdated עבור נסיעה א מחזירה רשימה של ציוני הדרך שנותרו (remainingWaypoints) שמכילה באיסוףנקודת הורדה.
  • getTrip() או הקריאה החוזרת (callback) onTripRemainingWaypointsUpdated עבור נסיעה B מחזירה רשימה של ציוני הדרך שנותרו (remainingWaypoints) שמכילה ב איסוףא הורדהב נשירה.

דוגמה

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

static final String PROJECT_ID = "my-rideshare-co-gcp-project";
static final String TRIP_A_ID = "share-trip-A";
static final String TRIP_B_ID = "share-trip-B";
static final String VEHICLE_ID = "Vehicle";

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

// Get Trip A and Trip B objects from either the Fleet Engine or storage.
Trip tripA = …;
Trip tripB = …;

TripServiceBlockingStub tripService = TripService.newBlockingStub(channel);

// The trip settings to update.
Trip trip = Trip.newBuilder()
    .setVehicleId(VEHICLE_ID)
    .addAllVehicleWaypoints(
        // This is where you define the arrival order for unvisited waypoints.
        // If you don’t specify an order, then the Fleet Engine adds Trip B’s
        // waypoints to the end of Trip A’s.
        ImmutableList.of(
            // Trip B’s pickup point.
            TripWaypoint.newBuilder()
                .setLocation(tripB.getPickupPoint())
                .setTripId(TRIP_B_ID)
                .setWaypointType(WaypointType.PICKUP_WAYPOINT_TYPE)
                .build(),
            // Trip A’s drop-off point.
            TripWaypoint.newBuilder()
                .setLocation(tripA.getDropoffPoint())
                .setTripId(TRIP_A_ID)
                .setWaypointType(WaypointType.DROP_OFF_WAYPOINT_TYPE)
                .build(),
            // Trip B’s drop-off point.
            TripWaypoint.newBuilder()
                .setLocation(tripB.getDropoffPoint())
                .setTripId(TRIP_B_ID)
                .setWaypointType(WaypointType.DROP_OFF_WAYPOINT_TYPE)
                .build()))
    .build();

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

// Error handling. If Fleet Engine has both a trip and vehicle with the IDs,
// and if the credentials validate, and if the given vehicle_waypoints list
// is valid, 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:          // Either the trip or vehicle does not exist.
      break;
    case PERMISSION_DENIED:
      break;
    case INVALID_REQUEST:    // vehicle_waypoints is invalid.
      break;
  }
  return;
}

שלב 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. הצגת התהליך באפליקציה לצרכנים

כדי לגשת לממשקי ה-API של רכיבי ממשק המשתמש של Rides and Deliveries:

דוגמה

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

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

כברירת מחדל, SDK מציג רק את הקטע הפעיל במסלול, אבל אפשר להציג את הקטע שנותר, שכולל את היעד.

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

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

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

דוגמה

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