Tạo và hiển thị các chuyến đi trong nhóm chung

Chuyến đi chung xe là những chuyến đi chung của nhiều người tiêu dùng đi chung xe. Điều này nghĩa là các chuyến đi diễn ra đồng thời, không độc lập. Cách thức hoạt động của xe này tương tự như cách hoạt động của xe đưa đón sân bay, ngoại trừ việc người lái xe cũng có thể trả khách dọc theo tuyến đường.

Điểm khác biệt chính giữa chuyến đi chung và chuyến đi một điểm đến là trong chuyến đi chung, nhà điều hành chuyến đi có thể vận chuyển nhiều hành khách cùng một lúc.

Hướng dẫn này sẽ hướng dẫn bạn thực hiện quy trình tạo chuyến đi chung cho nhóm. Ngoài ra, ứng dụng này cũng cho biết cách bạn có thể tích hợp chuyến đi đó với ứng dụng dành cho người tiêu dùng của bạn để khách hàng có thể hình dung tiến trình của chuyến đi từ điện thoại của họ. Bạn thực hiện tích hợp này bằng cách sử dụng SDK người tiêu dùng.

Bước 1. Tạo xe trong Fleet Engine

Phương tiện vận chuyển là đồ vật đại diện cho phương tiện trong nhóm phương tiện của bạn. Bạn phải tạo chúng trong Fleet Engine để có thể theo dõi chúng trong ứng dụng cho người dùng thông thường.

Bạn có thể tạo xe bằng một trong hai phương pháp sau:

gRPC
Gọi phương thức CreateVehicle() bằng thông báo yêu cầu CreateVehicleRequest. Bạn phải có đặc quyền Người dùng cấp cao của Fleet Engine để gọi được CreateVehicle().
Kiến trúc chuyển trạng thái đại diện (REST)
Gọi https://fleetengine.googleapis.com/v1/providers.vehicles.create.

Chú ý

Những điều cần lưu ý sau đây sẽ áp dụng khi bạn tạo phương tiện di chuyển.

  • Hãy nhớ đặt trạng thái ban đầu của xe thành OFFLINE. Điều này đảm bảo rằng Fleet Engine có thể tìm ra xe của bạn để so khớp chuyến đi.

  • provider_id của xe phải giống với mã dự án của dự án Google Cloud chứa Tài khoản dịch vụ dùng để gọi Fleet Engine. Mặc dù nhiều tài khoản dịch vụ có thể truy cập vào Fleet Engine cho cùng một nhà cung cấp dịch vụ đi chung xe, nhưng Fleet Engine hiện không hỗ trợ tài khoản dịch vụ từ nhiều Dự án Google Cloud khác nhau sử dụng cùng một xe.

  • Phản hồi được trả về từ CreateVehicle() chứa thực thể Vehicle. Thực thể này sẽ bị xoá sau 7 ngày nếu không được cập nhật bằng UpdateVehicle(). Bạn nên gọi GetVehicle() trước khi gọi CreateVehicle() để xác nhận rằng chưa có xe này. Nếu GetVehicle() trả về lỗi NOT_FOUND, thì bạn nên tiếp tục gọi CreateVehicle(). Để biết thêm thông tin, hãy xem bài viết Phương tiện và vòng đời của chúng.

Ví dụ:

Mã mẫu nhà cung cấp sau đây minh hoạ cách tạo một chiếc xe trong 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;
}

Để tạo một Vehicle hỗ trợ các chuyến đi qua nhóm chung, bạn phải thêm TripType.SHARED vào danh sách các loại chuyến đi được hỗ trợ trong đối tượng Vehicle được truyền đến CreateVehicleRequest.

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

Bước 2. Bật tính năng theo dõi vị trí

Tính năng theo dõi vị trí là hoạt động theo dõi vị trí của xe trong suốt chuyến đi, khi ứng dụng người lái gửi dữ liệu đo từ xa đến Fleet Engine, nơi chứa thông tin vị trí hiện tại của xe. Luồng thông tin vị trí được cập nhật liên tục này được dùng để truyền đạt tiến trình của xe trong suốt tuyến đường của chuyến đi. Khi bạn bật tính năng theo dõi vị trí, ứng dụng dành cho người lái xe sẽ bắt đầu gửi dữ liệu đo từ xa này với tần suất mặc định là 5 giây một lần.

Bạn bật tính năng theo dõi vị trí cho Android và iOS như sau:

Ví dụ:

Ví dụ về mã sau đây minh hoạ cách bật tính năng theo dõi vị trí.

Java

RidesharingVehicleReporter vehicleReporter = ...;

vehicleReporter.enableLocationTracking();

Kotlin

val vehicleReporter = ...

vehicleReporter.enableLocationTracking()

Swift

vehicleReporter.locationTrackingEnabled = true

Objective-C

_vehicleReporter.locationTrackingEnabled = YES;

Bước 3. Đặt trạng thái xe thành trực tuyến

Bạn đưa một chiếc xe vào dịch vụ (tức là để xe có thể sử dụng) bằng cách đặt trạng thái của xe thành trực tuyến, nhưng bạn không thể thực hiện việc này cho đến khi đã bật tính năng theo dõi vị trí.

Bạn đặt trạng thái của xe thành trực tuyến đối với Android và iOS như sau:

Ví dụ:

Mã ví dụ sau đây minh hoạ cách đặt trạng thái của xe thành ONLINE.

Java

vehicleReporter.setVehicleState(VehicleState.ONLINE);

Kotlin

vehicleReporter.setVehicleState(VehicleState.ONLINE)

Swift

vehicleReporter.update(.online)

Objective-C

[_vehicleReporter updateVehicleState:GMTDVehicleStateOnline];

Bước 4. Tạo chuyến đi trong Fleet Engine

Để tạo chuyến đi đi chung ở một nhóm, bạn sẽ tạo đối tượng Trip tương tự như đối với chuyến đi một điểm đến.

Chuyến đi là một đối tượng đại diện cho hành trình. Đó là các điểm toạ độ địa lý của bộ sưu tập, bao gồm cả điểm gốc, điểm tham chiếu và điểm trả. Bạn phải tạo một đối tượng Trip cho mỗi yêu cầu chuyến đi để yêu cầu đó có thể được so khớp với một xe và sau đó theo dõi.

Cung cấp các thuộc tính bắt buộc

Bạn phải điền vào các trường sau để tạo chuyến đi chung cho nhóm.

parent
Một chuỗi chứa mã nhà cung cấp. Mã này phải giống với mã dự án của dự án trên Google Cloud chứa Tài khoản dịch vụ dùng để gọi Fleet Engine
trip_id
Một chuỗi do bạn tạo để xác định duy nhất chuyến đi này.
trip
Trip đối tượng cần tạo.

Bạn cần đặt các trường sau đây trong đối tượng Trip được truyền đến CreateTripRequest:

trip_type
TripType.SHARED
pickup_point
Điểm xuất phát của chuyến đi.
dropoff_point
Điểm trả khách của chuyến đi. Bạn không bắt buộc phải sử dụng trường này khi tạo chuyến đi và bạn có thể đặt trường này sau bằng cách gọi UpdateTrip.

Ví dụ:

Mẫu tích hợp phần phụ trợ sau đây minh hoạ cách tạo một chuyến đi và tự động chỉ định cho một xe dưới dạng nhóm chung.

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

Bước 5. Cập nhật chuyến đi bằng mã xe và điểm tham chiếu

Bạn phải định cấu hình chuyến đi bằng mã xe để Fleet Engine có thể theo dõi xe dọc theo tuyến đường.

  • Bạn có thể cập nhật chuyến đi với mã xe bằng cách gọi điểm cuối UpdateTrip bằng UpdateTripRequest. Sử dụng trường update_mask để chỉ định rằng bạn đang cập nhật mã xe.

Bạn phải giới thiệu thứ tự các điểm tham chiếu chưa được ghé thăm trong tập hợp điểm tham chiếu trên phương tiện của chuyến đi (Trip.vehicle_waypoints). Fleet Engine sử dụng danh sách này để tự động cập nhật điểm tham chiếu chuyến đi cho tất cả các chuyến đi trong nhóm chung.

Ví dụ: hãy cân nhắc hai chuyến đi chung: Chuyến đi AChuyến B. Chuyến đi A đang trên đường đến địa điểm trả xe. Sau đó, Chuyến đi B được thêm vào cùng một xe. Trong một UpdateTripRequest cho Chuyến B, bạn đặt vehicleId, đồng thời đặt Trip.vehicle_waypoints thành thứ tự điểm tham chiếu tối ưu: B Đến lấy hàngA Trả xeB Trả khách.

  • Khi gọi getVehicle(), hệ thống sẽ trả về danh sách các điểm tham chiếu còn lại (remainingWaypoints) có chứa
    B Đến lấyA Trả xeB Bỏ xe.
  • getTrip() hoặc lệnh gọi lại onTripRemainingWaypointsUpdated cho Chuyến đi A sẽ trả về danh sách các điểm tham chiếu còn lại (remainingWaypoints) có chứa B Đến lấy hàngA Trả khách.
  • getTrip() hoặc lệnh gọi lại onTripRemainingWaypointsUpdated cho Chuyến đi B sẽ trả về danh sách các điểm tham chiếu còn lại (remainingWaypoints) có chứa B Trả xeA Trả xeB Trả xe.

Ví dụ:

Mẫu tích hợp phần phụ trợ sau đây minh hoạ cách cập nhật chuyến đi bằng mã nhận dạng xe và điểm tham chiếu cho hai chuyến đi chung xe.

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

Bước 6. Theo dõi thông tin cập nhật về chuyến đi trong ứng dụng dành cho người tiêu dùng

  • Đối với Android, bạn có thể theo dõi thông tin cập nhật dữ liệu của một chuyến đi bằng cách lấy đối tượng TripModel từ TripModelManager và đăng ký trình nghe TripModelCallback.

  • Đối với iOS, bạn có thể theo dõi thông tin cập nhật về dữ liệu của một chuyến đi bằng cách lấy đối tượng GMTCTripModel từ GMTCTripService và đăng ký một người đăng ký GMTCTripModelSubscriber.

Trình nghe TripModelCallback và người đăng ký GMTCTripModelSubscriber cho phép ứng dụng của bạn nhận thông tin cập nhật định kỳ về tiến trình chuyến đi trong mỗi lần làm mới dựa trên khoảng thời gian tự động làm mới. Chỉ những giá trị thay đổi mới có thể kích hoạt lệnh gọi lại. Nếu không, lệnh gọi lại sẽ vẫn ở chế độ im lặng.

Phương thức TripModelCallback.onTripUpdated()tripModel(_:didUpdate:updatedPropertyFields:) luôn được gọi, bất kể có thay đổi nào về dữ liệu.

Ví dụ 1

Mã mẫu sau đây minh hoạ cách lấy TripModel từ TripModelManager/GMTCTripService và thiết lập trình nghe trên đó.

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

Ví dụ 2

Mã mẫu sau đây minh hoạ cách thiết lập trình nghe TripModelCallback và người đăng ký 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

Bạn có thể truy cập thông tin về chuyến đi bất cứ lúc nào như sau:

  • Gọi phương thức SDK người dùng cho Android TripModel.getTripInfo(). Việc gọi phương thức này sẽ không buộc làm mới dữ liệu, mặc dù dữ liệu vẫn tiếp tục được làm mới ở tần suất làm mới.

  • Tải thuộc tính SDK người tiêu dùng cho iOS GMTCTripModel.currentTrip.

Bước 7. Hiển thị hành trình trong ứng dụng của người tiêu dùng

Bạn có thể truy cập vào các API phần tử trên giao diện người dùng của tính năng Đi lại và giao hàng như sau:

Ví dụ:

Ví dụ về mã sau đây minh hoạ cách bắt đầu giao diện người dùng chia sẻ hành trình.

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

Theo mặc định, Consumer SDK chỉ hiển thị chân đang hoạt động trong tuyến đường, nhưng bạn có thể hiển thị chân còn lại, bao gồm cả đích đến.

Nếu muốn hiển thị thông tin về điểm tham chiếu của các chuyến đi khác, bạn có thể truy cập tất cả các điểm tham chiếu liên quan đến chuyến đi như sau:

Bước 8. Quản lý trạng thái chuyến đi trong Fleet Engine

Bạn chỉ định trạng thái của chuyến đi bằng một trong các giá trị liệt kê TripStatus. Khi trạng thái của chuyến đi thay đổi (ví dụ: thay đổi từ ENROUTE_TO_PICKUP thành ARRIVED_AT_PICKUP), bạn phải cập nhật trạng thái chuyến đi thông qua Fleet Engine. Trạng thái chuyến đi luôn bắt đầu bằng giá trị NEW và kết thúc bằng giá trị COMPLETE hoặc CANCELED. Để biết thêm thông tin, hãy xem trip_status.

Ví dụ:

Mẫu tích hợp phần phụ trợ sau đây minh hoạ cách cập nhật trạng thái chuyến đi trong 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;
}