Bu eğitim, tek bir teslim alma ve bırakma seçeneği sunan bir gezi oluşturma ve ardından bu yolculuğu tüketiciyle paylaşma sürecinde size yol gösterir.
Ön koşullar
Bu eğiticiyi tamamlamak için aşağıdaki adımları tamamladığınızdan emin olun:
Fleet Engine'i kurun. Daha fazla bilgi için Fleet Engine: İlk kurulum sayfasını inceleyin.
Uygulamanızı Sürücü SDK'sı ile entegre edin. Daha fazla bilgi edinmek için Android için Sürücü SDK'sını Başlatma ve iOS için Sürücü SDK'sı için Entegrasyon Kılavuzu'na bakın.
Tüketiciye yönelik uygulamanızı Tüketici SDK'sı ile entegre edin. Daha fazla bilgi için Android için Tüketici SDK'sını Kullanmaya Başlama ve iOS için Tüketici SDK'sını Kullanmaya Başlama bölümlerine bakın.
Yetkilendirme jetonlarını ayarlayın. Yetkilendirme jetonları hakkında daha fazla bilgi edinmek için Fleet Engine'i Kullanmaya Başlama kılavuzundaki Yetkilendirme için JSON Web Jetonu oluşturma bölümüne ve Fleet Engine'in Tüketici SDK'sı dokümanlarındaki Kimlik doğrulama ve yetkilendirme bölümüne bakın.
1. Adım: Fleet Engine'de araç oluşturma
Araçlar, filonuzdaki araçları temsil eden nesnelerdir. Bunları tüketici uygulamasında izleyebilmek için Fleet Engine'de oluşturmanız gerekir.
Aşağıdaki iki yaklaşımdan birini kullanarak araç oluşturabilirsiniz:
- gRPC
CreateVehicleRequest
istek mesajıylaCreateVehicle()
yöntemini çağırın.CreateVehicle()
hizmetini aramak için Fleet Engine Süper Kullanıcısı ayrıcalıklarına sahip olmanız gerekir.- REST
https://fleetengine.googleapis.com/v1/providers.vehicles.create
numaralı telefonu arayın.
Uyarılar
Araç oluştururken aşağıdaki uyarılar geçerlidir.
Araç başlangıç durumunu
OFFLINE
olarak ayarladığınızdan emin olun. Bu sayede Fleet Engine, gezi eşleştirme için aracınızı bulabilir.Aracın
provider_id
değeri, Fleet Engine'i çağırmak için kullanılan Hizmet Hesaplarını içeren Google Cloud projesinin proje kimliğiyle aynı olmalıdır. Aynı araç paylaşımı sağlayıcısı için birden fazla hizmet hesabı Fleet Engine'e erişebilir ancak Fleet Engine, şu anda aynı araçlara erişen farklı Google Cloud Projelerine ait hizmet hesaplarını desteklememektedir.CreateVehicle()
öğesinden döndürülen yanıtVehicle
örneğini içeriyor. Örnek,UpdateVehicle()
kullanılarak güncellenmemişse yedi gün sonra silinir. Aracın zaten mevcut olmadığını doğrulamak içinCreateVehicle()
numaralı telefonu aramadan önceGetVehicle()
numaralı telefonu arayın.GetVehicle()
,NOT_FOUND
hatası döndürürseCreateVehicle()
çağrısıyla devam etmeniz gerekir. Daha fazla bilgi için Araçlar ve yaşam döngüleri başlıklı makaleyi inceleyin.
Örnek
Aşağıdaki sağlayıcı kod örneği, Fleet Engine'de nasıl araç oluşturulacağını gösterir.
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. adım: Konum izlemeyi etkinleştir
Konum izleme, seyahat sırasında aracın konumunun izlenmesini ifade eder. Sürücü uygulaması, bu noktada telemetriyi aracın mevcut konumunu içeren Fleet Engine'e gönderir. Sürekli güncellenen bu konum bilgisi akışı, aracın rota boyunca ilerlemesini aktarmak için kullanılır. Konum izlemeyi etkinleştirdiğinizde sürücü uygulaması, bu telemetriyi varsayılan sıklıkta beş saniyede bir göndermeye başlar.
Android ve iOS için konum izlemeyi şu şekilde etkinleştirirsiniz:
Android için Driver SDK'sı
enableLocationTracking()
yöntemini çağırın.iOS boole özelliği
locationTrackingEnabled
için Driver SDK'sınıtrue
olarak ayarlayın.
Örnek
Aşağıdaki kod örneğinde konum izlemenin nasıl etkinleştirileceği gösterilmektedir.
Java
RidesharingVehicleReporter vehicleReporter = ...;
vehicleReporter.enableLocationTracking();
Kotlin
val vehicleReporter = ...
vehicleReporter.enableLocationTracking()
Swift
vehicleReporter.locationTrackingEnabled = true
Objective-C
_vehicleReporter.locationTrackingEnabled = YES;
3. adım: Aracın durumunu online olarak ayarlayın
Bir aracı, durumunu çevrimiçi olarak ayarlayıp hizmete (yani kullanılabilir hale getirmek) getirirsiniz, ancak konum izlemeyi etkinleştirinceye kadar bunu yapamazsınız.
Android ve iOS için aracın durumunu çevrimiçi olarak ayarlarsınız:
Android için Driver SDK'sı
setVehicleState(VehicleState.ONLINE)
yöntemini çağırın.iOS için Driver SDK'sı
vehicleReporter.update(.online)
yöntemini çağırın.
Örnek
Aşağıdaki kod örneğinde, aracın durumunun nasıl ONLINE
olarak ayarlanacağı gösterilmektedir.
Java
vehicleReporter.setVehicleState(VehicleState.ONLINE);
Kotlin
vehicleReporter.setVehicleState(VehicleState.ONLINE)
Swift
vehicleReporter.update(.online)
Objective-C
[_vehicleReporter updateVehicleState:GMTDVehicleStateOnline];
4. Adım: Fleet Engine'de gezi oluşturma
Programatik olarak, Trip
, yolculuğu temsil eden bir nesnedir. Araçlarla eşleştirilip takip edilebilmeleri için her seyahat isteği için bir nesne oluşturmanız gerekir.
CreateTripRequest
istek mesajıylaCreateTrip()
yöntemini çağırarak gezi oluşturabilirsiniz.
Gerekli özellikler
Gezi oluşturmak için aşağıdaki alanlar gereklidir.
parent
- Sağlayıcı kimliğini içeren bir dize. Bu numara, Fleet Engine'i çağırmak için kullanılan Hizmet Hesaplarını içeren Google Cloud projesinin proje kimliğiyle aynı olmalıdır
trip_id
- Bu seyahati benzersiz bir şekilde tanımlayan, sizin oluşturduğunuz bir dizedir.
trip_type
TripType
numaralandırma değerlerinden biri (SHARED
veyaEXCLUSIVE
).pickup_point
- Gezinin kalkış noktası.
Gezi oluştururken number_of_passengers
, dropoff_point
ve vehicle_id
alanlarını sağlayabilirsiniz ancak bu alanlar zorunlu değildir.
Bir vehicle_id
sağladığınızda gezi, hedefi sürücü uygulamasında ayarlamak için kullanabileceğiniz kalan ara noktaların listesini içerir.
Örnek
Aşağıdaki örnekte, Grand Indonesia East Mall'a nasıl seyahat oluşturulacağı gösterilmektedir. İki yolculu bu yolculuk özeldir ve yeni durumundadır. Gezinin provider_id
değeri, proje kimliğiyle aynı olmalıdır. Örnekte, araç paylaşımı sağlayıcısı Google Cloud Projesini my-rideshare-co-gcp-project
proje kimliğiyle oluşturmuştur. Bu proje, Fleet Engine'i çağırmak için kullanılan bir hizmet hesabı içermelidir.
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. Adım: Sürücü uygulamasında hedefi ayarlayın
Bir tüketiciyi sürücüyle eşledikten sonra sürücü uygulamasında yolculuğun varış noktasını yapılandırmanız gerekir. Aracın varış noktasını, GetTrip()
, UpdateTrip()
ve GetVehicle()
tarafından döndürülen ara noktalar koleksiyonundan alabilirsiniz.
- Android için
setDestination()
yöntemini veya iOS için Gezinme SDK'sınısetDestinations()
çağırarak hedefi ayarlarsınız.
Tüketici uygulamasının geziyi düzgün bir şekilde oluşturması için setDestination()
bölgesine sağlanan coğrafi koordinatların (EnlBoy) seyahatin ara noktasındakilerle eşleşmesi gerekir. Daha fazla bilgi için Route to a Single Destination (Tek Bir Hedefe Rotaya Getirme) ve Route to multiple Destinations (Birden Çok Hedefe Rota Oluşturma) eğiticilerine göz atın.
Örnek
Aşağıdaki kod örneği, sürücü uygulamasında hedefin nasıl ayarlanacağını gösterir.
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. Adım: Tüketici uygulamasında gezi güncellemelerini dinleyin
Android'de,
TripModelManager
öğesinden birTripModel
nesnesi alarak ve birTripModelCallback
işleyicisi kaydederek geziye ait veri güncellemelerini dinleyebilirsiniz.iOS'te,
GMTCTripService
öğesinden birGMTCTripModel
nesnesi alarak ve birGMTCTripModelSubscriber
abonesi kaydederek bir geziye ait veri güncellemelerini dinleyebilirsiniz.
TripModelCallback
dinleyicisi ve GMTCTripModelSubscriber
abonesi, uygulamanızın her yenilemede otomatik yenileme aralığına göre periyodik olarak gezi durumu güncellemeleri almasına olanak tanır.
Yalnızca değişen değerler geri çağırmayı tetikleyebilir. Aksi takdirde, geri arama
sessiz kalır.
TripModelCallback.onTripUpdated()
ve tripModel(_:didUpdate:updatedPropertyFields:)
yöntemleri, veri değişikliklerinden bağımsız olarak her zaman çağrılır.
1. Örnek
Aşağıdaki kod örneğinde, TripModelManager
/GMTCTripService
kaynağından nasıl TripModel
edinileceği ve bunun için nasıl işleyici ayarlanacağı gösterilmektedir.
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. Örnek
Aşağıdaki kod örneğinde bir TripModelCallback
işleyicinin ve GMTCTripModelSubscriber
abonesinin nasıl oluşturulacağı gösterilmektedir.
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
Geziyle ilgili bilgilere aşağıdaki şekilde istediğiniz zaman erişebilirsiniz:
Android için Tüketici SDK'sı
TripModel.getTripInfo()
yöntemini çağırın. Bu yöntemin çağrılması verileri yenilemeye zorlamaz, ancak veriler yine de yenileme sıklığında yenilenmeye devam eder.iOS mülkü için
GMTCTripModel.currentTrip
Tüketici SDK'sını edinin.
7. Adım. Geziyi araç kimliğiyle güncelleyin
Fleet Engine'in aracı rota boyunca izleyebilmesi için yolculuğu araç kimliğiyle yapılandırmanız gerekir.
UpdateTrip
uç noktasınıUpdateTripRequest
ile çağırarak geziyi araç kimliğiyle güncelleyebilirsiniz. Araç kimliğini güncellediğinizi belirtmek içinupdate_mask
alanını kullanın.
Notlar
Geziyi oluştururken bir hedef belirtmezseniz, bunu dilediğiniz zaman buradan yapabilirsiniz.
Devam eden bir gezide aracı değiştirmeniz gerekirse yolculuğun durumunu tekrar "yeni" olarak ayarlamanız ve ardından yolculuğu (yukarıda yaptığınız gibi) yeni araç kimliğiyle güncellemeniz gerekir.
Örnek
Aşağıdaki kod örneğinde, araç kimliğiyle seyahatin nasıl güncelleneceği gösterilmektedir.
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. Adım: Yolculuğu tüketici uygulamasında gösterin
Yolculuklar ve Teslimatlar kullanıcı arayüzü öğesi API'lerine erişmek için ConsumerController
nesnesini kullanın.
Daha fazla bilgi için Kullanıcı arayüzü öğesi API'lerini kullanma bölümüne bakın.
Örnek
Aşağıdaki kod örneğinde, kullanıcı arayüzünün paylaşım yolculuğuna nasıl başlanacağı gösterilmektedir.
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. Adım: Fleet Engine'de gezi durumunu yönetme
Bir gezinin durumunu TripStatus
numaralandırma değerlerinden birini kullanarak belirtirsiniz. Bir gezinin durumu değiştiğinde (örneğin, ENROUTE_TO_PICKUP
değerinden ARRIVED_AT_PICKUP
değerine değiştirildiğinde) Fleet Engine üzerinden gezi durumunu güncellemeniz gerekir. Yolculuk durumu her zaman NEW
değeriyle başlar ve COMPLETE
veya CANCELED
değeriyle sona erer. Daha fazla bilgi için trip_status
adresini inceleyin.
Örnek
Aşağıdaki kod örneği, Filo Motoru'nda gezi durumunun nasıl güncelleneceğini gösterir.
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;
}