Anda dapat menggunakan Consumer SDK untuk membuat dan menjalankan aplikasi konsumen dasar yang terintegrasi dengan layanan backend Solusi Perjalanan dan Pengiriman On-demand. Anda dapat membuat aplikasi Progres Perjalanan dan Pesanan yang dapat menampilkan perjalanan aktif, merespons info terbaru perjalanan, dan menangani error perjalanan.
Karena Consumer SDK memiliki arsitektur modular, Anda dapat menggunakan bagian-bagian API yang ingin digunakan untuk aplikasi tertentu dan mengintegrasikannya dengan API Anda sendiri, layanan backend yang disediakan oleh Fleet Engine, dan API tambahan Google Maps Platform.
Persyaratan sistem minimum
Konfigurasi Project
Swift Package Manager
Consumer SDK dapat diinstal melalui Swift Package Manager. Untuk menambahkan SDK, pastikan Anda telah menghapus dependensi Consumer SDK yang ada.
Untuk menambahkan SDK ke project baru atau yang sudah ada, ikuti langkah-langkah berikut:
-
Buka
project
atauworkspace
Xcode, lalu buka File > Add Package Dependencies. - Masukkan https://github.com/googlemaps/ios-consumer-sdk sebagai URL, tekan Enter untuk menarik paket, lalu klik "Add Package".
-
Untuk menginstal
version
tertentu, tetapkan kolom Dependency Rule ke salah satu opsi berbasis versi. Untuk project baru, sebaiknya tentukan versi terbaru dan gunakan opsi "Versi Persis". Setelah selesai, klik "Add Package". -
Dari jendela Choose Package Products, pastikan
GoogleRidesharingConsumer
akan ditambahkan ke targetmain
yang ditentukan. Setelah selesai, klik "Add Package". -
Untuk memverifikasi penginstalan, buka panel
General
target Anda. Di Frameworks, Libraries, and Embedded Content, Anda akan melihat paket yang diinstal. Anda juga dapat melihat bagian "Package Dependencies" "Project Navigator" untuk memverifikasi paket dan versinya.
Untuk mengupdate package
untuk project yang sudah ada, ikuti langkah-langkah berikut:
Jika melakukan upgrade dari versi yang lebih lama dari 9.0.0, Anda harus menghapus dependensi berikut:
GoogleMapsBase
,GoogleMapsCore
, danGoogleMapsM4B
setelah proses upgrade. Jangan hapus dependensi untukGoogleMaps
. Untuk informasi selengkapnya, lihat Catatan Rilis Versi 9.0.0.Dari setelan konfigurasi project Xcode Anda, temukan Frameworks, Libraries, and Embedded Content. Gunakan tanda minus(-) untuk menghapus framework berikut:
GoogleMapsBase
(Hanya untuk upgrade dari versi sebelum 9.0.0)GoogleMapsCore
(Hanya untuk upgrade dari versi sebelum 9.0.0)GoogleMapsM4B
(Hanya untuk upgrade dari versi sebelum 9.0.0)
- Dari Xcode, buka "File > Packages > Update To Latest Package Versions".
- Untuk memverifikasi penginstalan, buka bagian Package Dependencies Project Navigator untuk memverifikasi paket dan versinya.
Untuk menghapus dependensi Consumer SDK yang sudah ada yang ditambahkan menggunakan
CocoaPods
, ikuti langkah-langkah berikut:
- Tutup ruang kerja Xcode Anda. Buka terminal dan jalankan perintah berikut:
sudo gem install cocoapods-deintegrate cocoapods-clean pod deintegrate pod cache clean --all
-
Hapus
Podfile
,Podfile.resolved
, dan Xcodeworkspace
jika Anda tidak menggunakannya untuk hal apa pun selain CocoaPods.
Untuk menghapus Consumer SDK yang sudah ada yang diinstal secara manual, ikuti langkah-langkah berikut:
Dari setelan konfigurasi project Xcode Anda, temukan Frameworks, Library, and Embedded Content. Gunakan tanda minus
(-)
untuk menghapus framework berikut:GoogleRidesharingConsumer.xcframework
Dari direktori level teratas project Xcode Anda, hapus paket
GoogleRidesharingConsumer
.
CocoaPods
Untuk mengonfigurasi Consumer SDK menggunakan CocoaPods, Anda memerlukan item berikut:
Alat CocoaPods: Untuk menginstal alat ini, buka Terminal dan jalankan perintah berikut.
sudo gem install cocoapods
Lihat Panduan Memulai CocoaPods untuk detail selengkapnya.
Buat Podfile untuk Consumer SDK dan gunakan untuk menginstal API beserta dependensinya. Pertama, buat file bernama Podfile di direktori project Anda. File ini menentukan dependensi project Anda. Kemudian, edit Podfile dan tambahkan dependensi Anda. Berikut adalah contoh yang menyertakan dependensi:
source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingConsumer' end
Simpan Podfile. Buka terminal, lalu buka direktori yang berisi Podfile:
cd <path-to-project>
Jalankan perintah pod install. Tindakan ini akan menginstal API yang ditentukan di Podfile, beserta dependensi yang mungkin dimilikinya.
pod install
Tutup Xcode, lalu buka (klik dua kali) file .xcworkspace project Anda untuk menjalankan Xcode. Untuk membuka project pada lain waktu, gunakan file .xcworkspace.
Penginstalan manual
XCFramework adalah paket biner yang Anda gunakan untuk menginstal Consumer SDK. Anda dapat menggunakan paket ini di beberapa platform, termasuk mesin yang menggunakan chipset M1. Panduan ini menunjukkan cara menambahkan XCFramework yang berisi Consumer SDK ke project Anda secara manual dan mengonfigurasi setelan build di Xcode.
Download resource dan biner SDK:
Ekstrak file zip untuk mengakses XCFramework dan resource.
Mulai Xcode dan buka project yang ada, atau buat project baru. Jika Anda baru menggunakan iOS, buat project baru lalu pilih template Aplikasi iOS.
Buat grup Framework dalam grup project Anda jika belum ada.
Untuk menginstal Consumer SDK, tarik file
GoogleRidesharingConsumer.xcframework
ke project Anda di bagian Frameworks, Libraries, and Embedded Content. Saat diminta, pilih Salin item jika diperlukan.Tarik
GoogleRidesharingConsumer.bundle
yang telah didownload ke direktori level teratas project Xcode Anda. Saat diminta, pilihCopy items if needed
.Pilih project Anda dari Navigator Project, lalu pilih target aplikasi Anda.
Buka tab Build Phases, dan di Link Binary with Libraries, tambahkan framework dan library berikut jika belum ada:
Accelerate.framework
CoreData.framework
CoreGraphics.framework
CoreImage.framework
CoreLocation.framework
CoreTelephony.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.tbd
libz.tbd
Metal.framework
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework
UIKit.framework
Pilih project Anda, bukan target tertentu, lalu buka tab Build Settings. Di bagian Other Linker Flags, tambahkan
-ObjC
untuk debug dan rilis. Jika setelan ini tidak terlihat, ubah filter di panel Setelan Build dari Basic menjadi All.
Memeriksa file Manifes Privasi Apple
Apple mewajibkan detail privasi aplikasi untuk aplikasi di App Store. Kunjungi halaman Detail Privasi Apple App Store untuk pembaruan dan informasi selengkapnya.
File Manifes Privasi Apple disertakan dalam paket resource untuk SDK. Untuk memverifikasi bahwa File Manifes Privasi telah disertakan, dan untuk memeriksa kontennya, buat arsip aplikasi dan buat laporan privasi dari arsip.
Integrasi aplikasi
Berikan token autentikasi
Saat aplikasi Consumer Anda meminta info terbaru perjalanan dari Fleet Engine, permintaan tersebut
harus menyertakan token akses yang valid. Untuk mengizinkan dan mengautentikasi permintaan ini,
Consumer SDK memanggil objek Anda yang sesuai dengan
protokol GMTCAuthorization
. Objek ini bertanggung jawab untuk menyediakan token akses yang diperlukan.
Sebagai developer aplikasi, Anda memilih cara token dibuat. Penerapan Anda harus memberikan kemampuan untuk melakukan hal berikut:
- Ambil token akses, kemungkinan dalam format JSON, dari server HTTPS.
- Uraikan dan simpan token dalam cache.
- Muat ulang token jika masa berlakunya sudah habis.
Untuk detail tentang token yang diharapkan oleh server Fleet Engine, lihat Membuat Token Web JSON (JWT) untuk otorisasi.
ID penyedia sama dengan Project ID Google Cloud. Untuk mengetahui informasi selengkapnya, lihat Mulai Menggunakan Fleet Engine.
Contoh berikut menerapkan penyedia token akses:
Swift
/*
* SampleAccessTokenProvider.swift
*/
import GoogleRidesharingConsumer
private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"
class SampleAccessTokenProvider: NSObject, GMTCAuthorization {
private struct AuthToken {
// The cached trip token.
let token: String
// Keep track of when the token expires for caching.
let expiration: TimeInterval
// Keep track of the trip ID the cached token is for.
let tripID: String
}
enum AccessTokenError: Error {
case missingAuthorizationContext
case missingData
}
private var authToken: AuthToken?
func fetchToken(
with authorizationContext: GMTCAuthorizationContext?,
completion: @escaping GMTCAuthTokenFetchCompletionHandler
) {
// Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
guard let authorizationContext = authorizationContext else {
completion(nil, AccessTokenError.missingAuthorizationContext)
return
}
let tripID = authorizationContext.tripID
// If appropriate, use the cached token.
if let authToken = authToken,
authToken.expiration > Date.now.timeIntervalSince1970 && authToken.tripID == tripID
{
completion(authToken.token, nil)
return
}
// Otherwise, try to fetch a new token from your server.
let request = URLRequest(url: URL(string: providerURL))
let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
guard let strongSelf = self else { return }
guard error == nil else {
completion(nil, error)
return
}
// Replace the following key values with the appropriate keys based on your
// server's expected response.
let tripTokenKey = "TRIP_TOKEN_KEY"
let tokenExpirationKey = "TOKEN_EXPIRATION"
guard let data = data,
let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let token = fetchData[tripTokenKey] as? String,
let expiration = fetchData[tokenExpirationKey] as? Double
else {
completion(nil, AccessTokenError.missingData)
return
}
strongSelf.authToken = AuthToken(token: token, expiration: expiration, tripID: tripID)
completion(token, nil)
}
task.resume()
}
}
Objective-C
/*
* SampleAccessTokenProvider.h
*/
#import <Foundation/Foundation.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
NS_ASSUME_NONNULL_BEGIN
@interface SampleAccessTokenProvider : NSObject <GMTCAuthorization>
@end
NS_ASSUME_NONNULL_END
/*
* SampleAccessTokenProvider.m
*/
#import "SampleAccessTokenProvider.h"
#import "GoogleRidesharingConsumer/GoogleRidesharingConsumer.h"
static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";
// SampleAccessTokenProvider.m
@implementation SampleAccessTokenProvider {
// The cached token with claims to the current trip.
NSString *_cachedTripToken;
// Keep track of the Trip ID the cached token is for.
NSString *_lastKnownTripID;
// Keep track of when tokens expire for caching.
NSTimeInterval _tokenExpiration;
}
- (void)fetchTokenWithContext:(nullable GMTCAuthorizationContext *)authorizationContext
completion:(nonnull GMTCAuthTokenFetchCompletionHandler)completion {
// Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
NSString *tripID = authorizationContext.tripID;
// Clear cached trip token if trip ID has changed.
if (![_lastKnownTripID isEqual:tripID]) {
_tokenExpiration = 0.0;
_cachedTripToken = nil;
}
_lastKnownTripID = tripID;
// Clear cached tripToken if it has expired.
if ([[NSDate date] timeIntervalSince1970] > _tokenExpiration) {
_cachedTripToken = nil;
}
// If appropriate, use the cached token.
if (_cachedTripToken) {
completion(_cachedTripToken, nil);
return;
}
// Otherwise, try to fetch a new token from your server.
NSURL *requestURL = [NSURL URLWithString:PROVIDER_URL];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:requestURL];
request.HTTPMethod = @"GET";
// Replace the following key values with the appropriate keys based on your
// server's expected response.
NSString *tripTokenKey = @"TRIP_TOKEN_KEY";
NSString *tokenExpirationKey = @"TOKEN_EXPIRATION";
__weak typeof(self) weakSelf = self;
void (^handler)(NSData *_Nullable data, NSURLResponse *_Nullable response,
NSError *_Nullable error) =
^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
typeof(self) strongSelf = weakSelf;
if (error) {
completion(nil, error);
return;
}
NSError *JSONError;
NSMutableDictionary *JSONResponse =
[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError];
if (JSONError) {
completion(nil, JSONError);
return;
} else {
// Sample code only. No validation logic.
id expirationData = JSONResponse[tokenExpirationKey];
if ([expirationData isKindOfClass:[NSNumber class]]) {
NSTimeInterval expirationTime = ((NSNumber *)expirationData).doubleValue;
strongSelf->_tokenExpiration = [[NSDate date] timeIntervalSince1970] + expirationTime;
}
strongSelf->_cachedTripToken = JSONResponse[tripTokenKey];
completion(JSONResponse[tripTokenKey], nil);
}
};
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *mainQueueURLSession =
[NSURLSession sessionWithConfiguration:config delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [mainQueueURLSession dataTaskWithRequest:request completionHandler:handler];
[task resume];
}
@end
Inisialisasi aplikasi
Swift
/*
* AppDelegate.swift
*/
import GoogleRidesharingConsumer
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register your API key for GMSServices.
GMSServices.provideAPIKey(yourMapsAPIKey)
// Set the instance of the SampleAccessTokenProvider.
GMTCServices.setAccessTokenProvider(SampleAccessTokenProvider(), providerID: yourProviderID)
// Other initialization code ...
return true
}
}
Objective-C
/*
* AppDelegate.m
*/
#import <GoogleMaps/GoogleMaps.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//Register your API key for GMSServices.
[GMSServices provideAPIKey:yourMapsAPIKey];
//Set the instance of the AccessTokenFactory.
[GMTCServices setAccessTokenProvider:[[SampleAccessTokenProvider alloc] init]
providerID:yourProviderID];
// Other initialization code ...
return YES;
}
@end
Integrasi tampilan peta
Melakukan inisialisasi tampilan peta
Contoh berikut menunjukkan cara melakukan inisialisasi GMTCMapView
.
Swift
/*
* MapViewController.swift
*/
class ViewController: UIViewController, GMTCMapViewDelegate {
private var rideSharingMap: GMTCMapView?
override func viewDidLoad() {
super.viewDidLoad()
self.rideSharingMap = GMTCMapView(frame: UIScreen.main.bounds)
self.rideSharingMap.delegate = self
self.rideSharingMap?.settings.myLocationButton = true
self.view.addSubview(self.rideSharingMap!)
...
}
Objective-C
/*
* MapViewController.h
*/
@interface MapViewController : UIViewController<GMTCMapViewDelegate>
...
@end
/*
* MapViewController.m
*/
@implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
...
self.mapView = [[GMTCMapView alloc] initWithFrame:CGRectZero];
self.mapView.settings.myLocationButton = YES;
self.mapView.delegate = self;
...
}
...
@end
Menangani peristiwa tampilan peta
Contoh berikut menunjukkan cara menerapkan delegasi untuk menangani peristiwa status pelanggan.
Swift
func mapViewDidInitialize(_ mapview: GMTCMapView) {
// Handle the update to the state of the map view to browsing.
}
func mapView(_ mapView: GMSMapView, didTapConsumerMarker mapMarker: GMSMarker, markerType: GMTCMapViewMarkerType) -> Bool {
// Handle the mapView marker was tapped.
}
Objective-C
/*
* MapViewController.m
*/
#pragma mark - GMTCMapViewDelegate implementation
// Handle state update of map view.
- (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
// Handle the update to the state of the map view to browsing.
}
- (void)mapView:(GMSMapView *)mapView
didTapConsumerMarker:(nonnull GMSMarker *)mapMarker
markerType:(GMTCMapViewMarkerType)markerType {
// Handle the mapView marker was tapped.
}
Berbagi perjalanan
Mulai perjalanan baru saat tampilan dimuat
Contoh berikut menunjukkan cara memulai berbagi perjalanan segera setelah
tampilan dimuat. Anda dapat mengumpulkan semua input pengguna seperti lokasi pengantaran dan penjemputan
dari ViewController
, lalu membuat ViewController
baru untuk memulai
berbagi perjalanan secara langsung.
Swift
/*
* MapViewController.swift
*/
override func viewDidLoad() {
super.viewDidLoad()
...
self.mapView = GMTCMapView(frame: UIScreen.main.bounds)
self.mapView.delegate = self
self.view.addSubview(self.mapView)
}
func mapViewDidInitializeCustomerState(_: GMTCMapView) {
self.mapView.pickupLocation = self.selectedPickupLocation
self.mapView.dropoffLocation = self.selectedDropoffLocation
self.startConsumerMatchWithLocations(
pickupLocation: self.mapView.pickupLocation!,
dropoffLocation: self.mapView.dropoffLocation!
) { [weak self] (tripName, error) in
guard let strongSelf = self else { return }
if error != nil {
// print error message.
return
}
let tripService = GMTCServices.shared().tripService
// Create a tripModel instance for listening the update of the trip
// specified by this trip name.
let tripModel = tripService.tripModel(forTripName: tripName)
// Create a journeySharingSession instance based on the tripModel
let journeySharingSession = GMTCJourneySharingSession(tripModel: tripModel)
// Add the journeySharingSession instance on the mapView for UI updating.
strongSelf.mapView.show(journeySharingSession)
// Register for the trip update events.
tripModel.register(strongSelf)
strongSelf.currentTripModel = tripModel
strongSelf.currentJourneySharingSession = journeySharingSession
strongSelf.hideLoadingView()
}
self.showLoadingView()
}
Objective-C
/*
* MapViewController.m
*/
- (void)viewDidLoad {
[super viewDidLoad];
...
self.mapView = [[GMTCMapView alloc] initWithFrame:CGRectZero];
self.mapView.delegate = self;
[self.view addSubview:self.mapView];
}
// Handle the callback when the GMTCMapView did initialized.
- (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
self.mapView.pickupLocation = self.selectedPickupLocation;
self.mapView.dropoffLocation = self.selectedDropoffLocation;
__weak __typeof(self) weakSelf = self;
[self startTripBookingWithPickupLocation:self.selectedPickupLocation
dropoffLocation:self.selectedDropoffLocation
completion:^(NSString *tripName, NSError *error) {
__typeof(self) strongSelf = weakSelf;
GMTCTripService *tripService = [GMTCServices sharedServices].tripService;
// Create a tripModel instance for listening to updates to the trip specified by this trip name.
GMTCTripModel *tripModel = [tripService tripModelForTripName:tripName];
// Create a journeySharingSession instance based on the tripModel.
GMTCJourneySharingSession *journeySharingSession =
[[GMTCJourneySharingSession alloc] initWithTripModel:tripModel];
// Add the journeySharingSession instance on the mapView for updating the UI.
[strongSelf.mapView showMapViewSession:journeySharingSession];
// Register for trip update events.
[tripModel registerSubscriber:self];
strongSelf.currentTripModel = tripModel;
strongSelf.currentJourneySharingSession = journeySharingSession;
[strongSelf hideLoadingView];
}];
[self showLoadingView];
}
Membatalkan perjalanan aktif
Contoh berikut menunjukkan cara mereset perjalanan yang aktif saat ini.
Swift
/*
* MapViewController.swift
*/
func cancelCurrentActiveTrip() {
// Stop the tripModel
self.currentTripModel.unregisterSubscriber(self)
// Remove the journey sharing session from the mapView's UI stack.
self.mapView.hide(journeySharingSession)
}
Objective-C
/*
* MapViewController.m
*/
- (void)cancelCurrentActiveTrip {
// Stop the tripModel
[self.currentTripModel unregisterSubscriber:self];
// Remove the journey sharing session from the mapView's UI stack.
[self.mapView hideMapViewSession:journeySharingSession];
}
Memantau info terbaru perjalanan
Contoh berikut menunjukkan cara mendaftarkan callback tripModel
.
Swift
/*
* MapViewController.swift
*/
override func viewDidLoad() {
super.viewDidLoad()
// Register for trip update events.
self.currentTripModel.register(self)
}
Objective-C
/*
* MapViewController.m
*/
- (void)viewDidLoad {
[super viewDidLoad];
// Register for trip update events.
[self.currentTripModel registerSubscriber:self];
...
}
Contoh berikut menunjukkan cara membatalkan pendaftaran callback
tripModel
.
Swift
/*
* MapViewController.swift
*/
deinit {
self.currentTripModel.unregisterSubscriber(self)
}
Objective-C
/*
* MapViewController.m
*/
- (void)dealloc {
[self.currentTripModel unregisterSubscriber:self];
...
}
Contoh berikut menunjukkan cara menerapkan protokol GMTCTripModelSubscriber
untuk menangani callback saat status perjalanan diperbarui.
Swift
/*
* MapViewController.swift
*/
func tripModel(_: GMTCTripModel, didUpdate trip: GMTSTrip?, updatedPropertyFields: GMTSTripPropertyFields) {
// Update the UI with the new `trip` data.
self.updateUI(with: trip)
}
func tripModel(_: GMTCTripModel, didUpdate tripStatus: GMTSTripStatus) {
// Handle trip status did change.
}
func tripModel(_: GMTCTripModel, didUpdateActiveRouteRemainingDistance activeRouteRemainingDistance: Int32) {
// Handle remaining distance of active route did update.
}
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.
}
func tripModel(_: GMTCTripModel, didUpdateActiveRouteTraffic activeRouteTraffic: GMTSTrafficData?) {
// Handle trip active route traffic being updated.
}
Objective-C
/*
* MapViewController.m
*/
#pragma mark - GMTCTripModelSubscriber implementation
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateTrip:(nullable GMTSTrip *)trip
updatedPropertyFields:(enum 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
didUpdateActiveRouteRemainingDistance:(int32_t)activeRouteRemainingDistance {
// Handle remaining distance of active route did update.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateActiveRoute:(nullable NSArray<GMTSLatLng *> *)activeRoute {
// Handle trip active 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.
}
- (void)tripModel:(GMTCTripModel *)tripModel
didUpdateActiveRouteTraffic:(nullable GMTSTrafficData *)activeRouteTraffic {
// Handle trip active route traffic being updated.
}
Penanganan error
Jika berlangganan tripModel dan terjadi error, Anda bisa mendapatkan callback tripModel dengan menerapkan metode delegasi tripModel(_:didFailUpdateTripWithError:)
. Fleet Engine menghasilkan pesan error yang mengikuti standar Error Google Cloud. Untuk mengetahui definisi pesan error detail dan semua kode error, lihat dokumentasi Error Google Cloud.
Secara khusus, untuk pemantauan perjalanan, diperlukan penyediaan token autentikasi yang valid. 401 UNAUTHENTICATED
akan dimunculkan jika tidak ada kredensial autentikasi
yang valid, seperti masa berlaku token habis.403 PERMISSION_DENIED
akan dimunculkan jika
pemanggil tidak memiliki izin untuk memanggil API tertentu (misalnya, pengguna dengan peran
konsumen mencoba memanggil updateTrip), atau permintaan tidak memiliki Vehicle_id/trip_id
yang valid dalam token JWT.
Untuk informasi selengkapnya, lihat Penanganan Error SDK Konsumen.
Penyesuaian UI
Mendapatkan dan menetapkan opsi UI polyline kustom
Contoh berikut menunjukkan cara menetapkan opsi UI kustom untuk polyline.
Swift
/** MapViewController.swift */
func updatePolylineUIOptions() {
// The polyline type that you would like to set custom UI options for.
let customizablePolylineType = GMTCPolylineType.activeRoute
let polylineStyleOptions = GMTCMutablePolylineStyleOptions()
polylineStyleOptions.strokeWidth = 8.0
polylineStyleOptions.strokeColor = .blue
polylineStyleOptions.isVisible = true
polylineStyleOptions.zIndex = 1000
polylineStyleOptions.isGeodesic = true
let coordinator = self.mapView.consumerMapStyleCoordinator
coordinator.setPolylineStyleOptions(polylineStyleOptions, polylineType:customizablePolylineType)
}
Objective-C
/** MapViewController.m */
- (void)updatePolylineUIOptions {
// The polyline type that you would like to set custom UI options for.
GMTCPolylineType customizablePolylineType = GMTCPolylineTypeActiveRoute;
GMTCMutablePolylineStyleOptions *polylineStyleOptions =
[[GMTCMutablePolylineStyleOptions alloc] init];
polylineStyleOptions.strokeWidth = 8.0;
polylineStyleOptions.strokeColor = [UIColor blueColor];
polylineStyleOptions.isVisible = YES;
polylineStyleOptions.zIndex = 1000;
polylineStyleOptions.isGeodesic = YES;
[[_mapView consumerMapStyleCoordinator] setPolylineStyleOptions:polylineStyleOptions
polylineType:customizablePolylineType];
}
Mendapatkan dan menetapkan opsi UI penanda kustom
Contoh berikut menunjukkan cara menetapkan opsi UI kustom untuk penanda.
Swift
/** MapViewController.swift */
func updateMarkerUIOptions() {
let customizableMarkerType = GMTCCustomizableMarkerType.tripVehicle
let markerStyleOptions = GMTCMutableMarkerStyleOptions()
markerStyleOptions.groundAnchor = groundAnchor
markerStyleOptions.isVisible = true
markerStyleOptions.icon = icon
markerStyleOptions.zIndex = 100
markerStyleOptions.isFlat = false
let coordinator = self.mapView.consumerMapStyleCoordinator
coordinator.setMarkerStyleOptions(markerStyleOptions, markerType: customizableMarkerType)
}
Objective-C
/** MapViewController.m */
- (void)updateMarkerUIOptions {
// The marker type that you would like to set custom UI options for.
GMTCCustomizableMarkerType customizableMarkerType = GMTCCustomizableMarkerTypeTripVehicle;
GMTCMutableMarkerStyleOptions *markerStyleOptions =
[[GMTCMutableMarkerStyleOptions alloc] init];
markerStyleOptions.groundAnchor = groundAnchor;
markerStyleOptions.isVisible = YES;
markerStyleOptions.icon = icon;
markerStyleOptions.zIndex = 100;
markerStyleOptions.isFlat = NO;
[[_mapView consumerMapStyleCoordinator] setMarkerStyleOptions:markerStyleOptions markerType:customizableMarkerType];
}
Menyesuaikan zoom kamera
Tombol Lokasiku di Maps SDK for iOS memusatkan kamera pada lokasi perangkat.
Jika ada sesi Berbagi Perjalanan yang aktif, Anda dapat menempatkan kamera di tengah untuk fokus pada perjalanan, bukan hanya pada lokasi perangkat.
Consumer SDK menyediakan fitur kamera otomatis yang diaktifkan secara default. Kamera akan memperbesar untuk fokus pada rute berbagi perjalanan dan titik jalan perjalanan berikutnya.
Jika memerlukan kontrol lebih besar terhadap perilaku kamera, Anda dapat menonaktifkan atau mengaktifkan
fitur kamera otomatis menggunakan
properti
isAllowCameraAutoUpdate
.
Untuk penyesuaian kamera lainnya, lihat Maps SDK for iOS Memindahkan kamera.