Mit dem Consumer SDK können Sie eine einfache Nutzer-App erstellen und ausführen, die in die Backend-Dienste der On-Demand-Lösung „Rides and Deliveries“ eingebunden ist. Sie können eine App für Fahrten und Bestellfortschritte erstellen, mit der Sie eine aktive Fahrt anzeigen, auf Fahrtaktualisierungen reagieren und Fahrtfehler beheben können.
Da das Consumer SDK eine modulare Architektur hat, können Sie die Teile der API, die Sie für Ihre App verwenden möchten, verwenden und in Ihre eigenen APIs, die von Fleet Engine bereitgestellten Back-End-Dienste und weitere APIs der Google Maps Platform einbinden.
Mindestsystemanforderungen
Projektkonfiguration
Swift-Paketmanager
Das Consumer SDK kann über den Swift Package Manager installiert werden. Entfernen Sie vor dem Hinzufügen des SDK alle vorhandenen Consumer SDK-Abhängigkeiten.
So fügen Sie das SDK einem neuen oder vorhandenen Projekt hinzu:
-
Öffnen Sie
project
oderworkspace
in Xcode und wählen Sie dann Datei > Paketabhängigkeiten hinzufügen aus. - Geben Sie https://github.com/googlemaps/ios-consumer-sdk als URL ein, drücken Sie die Eingabetaste, um das Paket abzurufen, und klicken Sie auf „Paket hinzufügen“.
-
Wenn Sie eine bestimmte
version
installieren möchten, setzen Sie das Feld Abhängigkeitsregel auf eine der versionsbasierten Optionen. Bei neuen Projekten empfehlen wir, die neueste Version anzugeben und die Option „Exakte Version“ zu verwenden. Klicke anschließend auf „Paket hinzufügen“. -
Prüfen Sie im Fenster Paketprodukte auswählen, ob
GoogleRidesharingConsumer
zum festgelegtenmain
-Ziel hinzugefügt wird. Klicke anschließend auf „Paket hinzufügen“. -
Um die Installation zu prüfen, gehen Sie zum Bereich
General
Ihres Ziels. Unter Frameworks, Bibliotheken und eingebettete Inhalte sollten die installierten Pakete angezeigt werden. Sie können auch im Abschnitt „Paketabhängigkeiten“ im „Project Navigator“ das Paket und seine Version prüfen.
So aktualisieren Sie die package
für ein vorhandenes Projekt:
- Gehen Sie in Xcode zu „File > Packages > Update To Recent Package Versions“ (Datei > Pakete> Auf neueste Paketversionen aktualisieren).
- Wenn Sie die Installation prüfen möchten, rufen Sie in der Projektnavigation den Bereich Paketabhängigkeiten auf. Dort sehen Sie das Paket und seine Version.
So entfernen Sie vorhandene Consumer SDK-Abhängigkeiten, die mit CocoaPods
hinzugefügt wurden:
- Schließen Sie den Xcode-Arbeitsbereich. Öffnen Sie das Terminal und führen Sie den folgenden Befehl aus:
sudo gem install cocoapods-deintegrate cocoapods-clean pod deintegrate pod cache clean --all
-
Entferne
Podfile
,Podfile.resolved
und den Xcodeworkspace
, wenn du sie ausschließlich für CocoaPods verwendest.
So entfernen Sie das vorhandene Consumer SDK, das manuell installiert wurde:
Suchen Sie in den Konfigurationseinstellungen Ihres Xcode-Projekts Frameworks, Bibliotheken und eingebettete Inhalte. Verwenden Sie das Minuszeichen
(-)
, um das folgende Framework zu entfernen:GoogleRidesharingConsumer.xcframework
Entfernen Sie das Bundle
GoogleRidesharingConsumer
aus dem Verzeichnis der obersten Ebene Ihres Xcode-Projekts.
CocoaPods
Um das Consumer SDK mit CocoaPods zu konfigurieren, benötigen Sie Folgendes:
CocoaPods-Tool: Öffnen Sie zum Installieren dieses Tools das Terminal und führen Sie den folgenden Befehl aus.
sudo gem install cocoapods
Weitere Informationen findest du im Startleitfaden zu CocoaPods.
Erstellen Sie eine Podfile-Datei für das Consumer SDK und installieren Sie damit die API und die zugehörigen Abhängigkeiten. Zuerst erstellen Sie in Ihrem Projektverzeichnis eine Datei namens Podfile. Diese Datei definiert die Abhängigkeiten Ihres Projekts. Bearbeiten Sie dann die Podfile-Datei und fügen Sie die Abhängigkeiten hinzu. Hier ist ein Beispiel, das die Abhängigkeiten enthält:
source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingConsumer' end
Speichern Sie die Podfile-Datei. Öffnen Sie ein Terminal und rufen Sie das Verzeichnis auf, das die Podfile-Datei enthält:
cd <path-to-project>
Führen Sie den Befehl "pod install" aus. Dadurch werden die in der Podfile-Datei angegebenen APIs und alle zugehörigen Abhängigkeiten installiert.
pod install
Schließen Sie Xcode und öffnen Sie per Doppelklick die .xcworkspace-Datei Ihres Projekts, um Xcode zu starten. Verwenden Sie die .xcworkspace-Datei, um das Projekt später zu öffnen.
Manuelle Installation
Ein XCFramework ist ein Binärpaket, mit dem Sie das Consumer SDK installieren. Sie können dieses Paket auf mehreren Plattformen verwenden, einschließlich Maschinen mit dem M1-Chipsatz. In dieser Anleitung wird beschrieben, wie Sie das XCFramework mit dem Consumer SDK manuell zu Ihrem Projekt hinzufügen und die Build-Einstellungen in Xcode konfigurieren.
Laden Sie die SDK-Binärdatei und die Ressourcen herunter:
Entpacken Sie die ZIP-Dateien, um auf XCFramework und Ressourcen zuzugreifen.
Starten Sie Xcode und öffnen Sie entweder ein vorhandenes Projekt oder erstellen Sie ein neues. Wenn Sie neu bei iOS sind, erstellen Sie ein neues Projekt und wählen Sie die Vorlage für iOS-Apps aus.
Erstellen Sie eine Frameworks-Gruppe in Ihrer Projektgruppe, falls noch keine vorhanden ist.
Ziehen Sie die Datei
GoogleRidesharingConsumer.xcframework
unter Frameworks, Bibliotheken und eingebettete Inhalte in Ihr Projekt, um das Consumer SDK zu installieren. Wenn Sie dazu aufgefordert werden, wählen Sie bei Bedarf Elemente kopieren aus.Ziehen Sie das heruntergeladene
GoogleRidesharingConsumer.bundle
in das Verzeichnis der obersten Ebene Ihres Xcode-Projekts. Wenn Sie dazu aufgefordert werden, wählen SieCopy items if needed
aus.Wählen Sie Ihr Projekt im Project Navigator und dann das Ziel Ihrer Anwendung aus.
Öffnen Sie den Tab „Build Phases“ (Build-Phasen) und fügen Sie unter „Link Binary with Libraries“ (Binärdatei mit Bibliotheken verknüpfen) die folgenden Frameworks und Bibliotheken hinzu, sofern sie noch nicht vorhanden sind:
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
Wählen Sie Ihr Projekt anstelle eines bestimmten Ziels aus und öffnen Sie den Tab Build Settings (Build-Einstellungen). Fügen Sie im Bereich Other Linker Flags (Weitere Verknüpfungs-Flags)
-ObjC
für die Fehlerbehebung und den Release hinzu. Wenn diese Einstellungen nicht sichtbar sind, ändern Sie den Filter in der Build-Einstellungsleiste von Basic in All.
Apple Privacy Manifest-Datei hinzufügen
- Laden Sie das Privacy Manifest-Bundle für das Consumer SDK for iOS herunter: GoogleRidesharingConsumerPrivacy.
- Extrahieren Sie die Datei, um auf
GoogleRidesharingConsumerPrivacy.bundle
zuzugreifen. - Fügen Sie
GoogleRidesharingConsumerPrivacy.bundle
mit einer dieser Methoden in die Xcode-Projektnavigation ein. Das Kästchen „Zu Zielen hinzufügen“ muss für das Ziel Ihrer App aktiviert sein. Nach dem Hinzufügen wird die PrivacyInfo-Datei im Projektnavigator angezeigt und Sie können sich die Werte ansehen. - Prüfen Sie, ob das Datenschutzmanifest hinzugefügt wurde. Erstellen Sie dazu ein Archiv Ihrer App und generieren Sie aus dem Archiv einen Datenschutzbericht.
Anwendungseinbindung
Authentifizierungstoken angeben
Wenn Ihre Consumer-App Fahrtaktualisierungen von Fleet Engine anfordert, müssen die Anfragen gültige Zugriffstokens enthalten. Zum Autorisieren und Authentifizieren dieser Anfragen ruft das Consumer SDK das Objekt auf, das dem GMTCAuthorization
-Protokoll entspricht. Das Objekt ist für die Bereitstellung des erforderlichen Zugriffstokens verantwortlich.
Als App-Entwickler entscheiden Sie, wie Tokens generiert werden. Ihre Implementierung sollte Folgendes ermöglichen:
- Rufen Sie ein Zugriffstoken, möglicherweise im JSON-Format, von einem HTTPS-Server ab.
- Parsen Sie das Token und speichern Sie es im Cache.
- Aktualisieren Sie das Token, wenn es abläuft.
Weitere Informationen zu den vom Fleet Engine-Server erwarteten Tokens finden Sie unter JSON-Webtoken (JWT) für die Autorisierung erstellen.
Die Anbieter-ID ist mit der Google Cloud-Projekt-ID identisch. Weitere Informationen finden Sie unter Erste Schritte mit Fleet Engine.
Im folgenden Beispiel wird ein Zugriffstoken-Anbieter implementiert:
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
Anwendungsinitialisierung
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
Integration der Kartenansicht
Kartenansicht initialisieren
Das folgende Beispiel zeigt, wie GMTCMapView
initialisiert wird.
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
Kartenansichtsereignisse verarbeiten
Das folgende Beispiel zeigt, wie ein Bevollmächtigter zur Verarbeitung von Kundenstatusereignissen implementiert wird.
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.
}
Reise teilen
Neue Fahrt starten, nachdem die Ansicht geladen wurde
Das folgende Beispiel zeigt, wie Sie direkt nach dem Laden der Ansicht eine Freigabe einer Journey starten. Sie können alle Nutzereingaben, z. B. Ein- und Ausstiegsorte aus einer ViewController
, erfassen und dann eine neue ViewController
erstellen, um die Fahrt direkt teilen zu können.
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];
}
Aktive Fahrt stornieren
Das folgende Beispiel zeigt, wie die aktuell aktive Fahrt zurückgesetzt wird.
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];
}
Benachrichtigungen zu Fahrten erhalten
Das folgende Beispiel zeigt, wie der tripModel
-Callback registriert wird.
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];
...
}
Das folgende Beispiel zeigt, wie die Registrierung des tripModel
-Callbacks abgebrochen wird.
Swift
/*
* MapViewController.swift
*/
deinit {
self.currentTripModel.unregisterSubscriber(self)
}
Objective-C
/*
* MapViewController.m
*/
- (void)dealloc {
[self.currentTripModel unregisterSubscriber:self];
...
}
Das folgende Beispiel zeigt, wie das GMTCTripModelSubscriber
-Protokoll für die Verarbeitung von Callbacks implementiert wird, wenn der Fahrtstatus aktualisiert wird.
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.
}
Fehlerbehandlung
Wenn Sie „tripModel“ abonniert haben und ein Fehler auftritt, können Sie den Callback von „tripModel“ durch Implementierung der Delegatmethode tripModel(_:didFailUpdateTripWithError:)
abrufen. Fleet Engine hat die Fehlermeldung generiert, die dem Google Cloud-Fehlerstandard entspricht. Die detaillierte Fehlermeldungsdefinition und alle Fehlercodes finden Sie in der Google Cloud-Fehlerdokumentation.
Insbesondere für die Fahrtüberwachung muss ein gültiges Authentifizierungstoken angegeben werden. 401 UNAUTHENTICATED
wird ausgelöst, wenn keine gültigen Anmeldedaten für die Authentifizierung vorhanden sind, z. B. wenn das Token abgelaufen ist. 403 PERMISSION_DENIED
wird ausgelöst, wenn der Aufrufer keine Berechtigung zum Aufrufen einer bestimmten API hat (z. B. wenn ein Nutzer mit Nutzerrolle versucht, „updateTrip“ aufzurufen) oder die Anfrage keine gültige Fahrzeug-ID/Trip_id im JWT-Token enthält.
Weitere Informationen findest du unter Fehlerbehandlung im Consumer SDK.
UI-Anpassung
UI-Optionen für benutzerdefinierte Polylinien abrufen und festlegen
Das folgende Beispiel zeigt, wie Sie benutzerdefinierte UI-Optionen für Polylinien festlegen.
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];
}
UI-Optionen für benutzerdefinierte Markierungen abrufen und festlegen
Das folgende Beispiel zeigt, wie benutzerdefinierte UI-Optionen für Markierungen festgelegt werden.
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];
}
Kamerazoom anpassen
Über die Schaltfläche Mein Standort im Maps SDK for iOS wird die Kamera auf den Gerätestandort zentriert.
Wenn eine Sitzung aktiv ist, können Sie die Kamera zentrieren, um den Fokus auf die Fahrt statt nur auf den Gerätestandort zu legen.
Das Consumer SDK bietet eine automatische Kamerafunktion, die standardmäßig aktiviert ist. Die Kamera zoomt, um die gemeinsame Route und den nächsten Wegpunkt zu fokussieren.
Wenn Sie mehr Kontrolle über das Kameraverhalten benötigen, können Sie die automatische Kamerafunktion über die Eigenschaft isAllowCameraAutoUpdate
deaktivieren oder aktivieren.
Weitere Informationen zur Kameraanpassung finden Sie unter Maps SDK for iOS Bewegen der Kamera.