Consumer SDK for iOS スタートガイド

Consumer SDK を使用すると、Terraform から基本的な オンデマンド配車と配達ソリューションのバックエンド サービスと統合されたユーザーアプリ。Google Chat では アクティブなルートを表示できる、移動および注文状況アプリを作成する ルート更新情報への応答、ルートエラーの処理を行います。

Consumer SDK はモジュラー アーキテクチャなので、 特定のアプリに必要な API の部分を使用できるため、 独自の API、Fleet が提供するバックエンド サービスと統合できます。 Google Maps Platform の追加 API です。

最小システム要件

  • モバイル デバイスに iOS 14 以降が搭載されている必要があります。
  • Xcode バージョン 15 以降。
  • プロジェクト構成

    Swift Package Manager

    Consumer SDK は でインストールできます。 Swift Package Manager。SDK を追加するには、 既存の Consumer SDK の依存関係が削除されました。

    新規または既存のプロジェクトに SDK を追加する手順は次のとおりです。

    1. Xcode project または workspace を開き、[File >パッケージの依存関係を追加する
    2. URL として「https://github.com/googlemaps/ios-consumer-sdk」と入力し、Enter キーを押します。 [パッケージを追加]をクリックします
    3. 特定の version をインストールするには、[Dependency Rule] フィールドを次のいずれかに設定します。 オプションを提供します。新しいプロジェクトの場合は、最新バージョンと 1 つのバージョンを 「正確なバージョン」を使用して選択します。完了したら、[Add Package] をクリックします。
    4. [Choose Package Products] ウィンドウで、GoogleRidesharingConsumer が以下に追加されることを確認します。 指定したmainの目標値。完了したら、[Add Package] をクリックします。
    5. インストールを確認するには、ターゲットの General ペインに移動します。 [Frameworks, Libraries, and Embedded Content] に、インストールされたパッケージが表示されます。 [Package Dependencies] ビューもセクション(プロジェクト ナビゲーター) パッケージとそのバージョンを確認します。

    既存のプロジェクトの package を更新する手順は次のとおりです。

    1. 9.0.0 より前のバージョンからアップグレードする場合は、 次の依存関係: GoogleMapsBaseGoogleMapsCore、 アップグレード後に GoogleMapsM4B。次の依存関係を削除しないでください。 GoogleMaps。詳しくは、 バージョン 9.0.0 リリースノート

      Xcode プロジェクト構成設定で、フレームワーク、ライブラリ、 および埋め込みコンテンツをご覧ください。マイナス記号(-)を使用して、次のフレームワークを削除します。

      • GoogleMapsBase(9.0.0 より前のバージョンからのアップグレードのみ)
      • GoogleMapsCore(9.0.0 より前のバージョンからのアップグレードのみ)
      • GoogleMapsM4B(9.0.0 より前のバージョンからのアップグレードのみ)
    2. Xcode で、[File] > [パッケージ >最新のパッケージ バージョンへの更新」を選択します。
    3. インストールを確認するには、Project Navigator の [Package Dependencies] セクションに移動します。 パッケージとそのバージョンを確認します。
    で確認できます。 <ph type="x-smartling-placeholder">

    以下を使用して追加された既存の Consumer SDK 依存関係を削除するには、 CocoaPods の手順は次のとおりです。

    1. Xcode ワークスペースを閉じます。ターミナルを開き、次のコマンドを実行します。
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
    2. PodfilePodfile.resolved、および CocoaPods 以外で使用していない場合には、Xcode workspace です。

    インストールされている既存の Consumer SDK を削除するには 次の操作を行います。

    1. Xcode プロジェクト構成設定で、フレームワーク、 ライブラリ、および埋め込みコンテンツマイナス記号(-)を使って削除します。 次のフレームワークを使用します。

      • GoogleRidesharingConsumer.xcframework
    2. Xcode プロジェクトの最上位ディレクトリから、 GoogleRidesharingConsumer セット。

    CocoaPods

    CocoaPods を使用して Consumer SDK を構成するには: 次のアイテムが必要です。

    • CocoaPods ツール: このツールをインストールするには、ターミナルを開いて次のコマンドを実行します。 次のコマンドを実行します。

      sudo gem install cocoapods
      

    詳しくは、CocoaPods のスタートガイド ガイド 表示されます。

    1. Consumer SDK 用の Podfile を作成して使用する API とその依存関係をインストールします。まず、先ほど作成した Podfile にコピーします。このファイルでは、 確認します。次に、Podfile を編集して依存関係を追加します。こちらの 依存関係を含む例を以下に示します。

        source "https://github.com/CocoaPods/Specs.git"
      
        target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
          pod 'GoogleRidesharingConsumer'
        end
      
    2. Podfile を保存します。ターミナルを開き、ターミナルを含むディレクトリに移動します。 Podfile:

      cd <path-to-project>
      
    3. Pod インストール コマンドを実行します。これにより、指定した API がインストールされます。 Podfile とそれらの依存関係が存在します。

      pod install
      
    4. Xcode を閉じて、プロジェクトの .xcworkspace を開く(ダブルクリック) Xcode を起動します。後でプロジェクトを開くには、.xcworkspace 表示されます。

    で確認できます。

    手動インストール

    XCFramework は、インストールに使用するバイナリ パッケージで、 Consumer SDKこのパッケージは複数の 搭載されています。このガイドでは、 XCFramework を手動で追加し、 コンシューマ SDK をプロジェクトに追加して、 Xcode でビルド設定を作成します。

    SDK バイナリとリソースをダウンロードします。

    1. 圧縮されたファイルを解凍して、XCFramework とリソースにアクセスします。

    2. Xcode を起動し、既存のプロジェクトを開くか、新しいプロジェクトを作成します。 できます。iOS を初めて使用する場合は、新しいプロジェクトを作成して [iOS] を選択します。 アプリ テンプレート。

    3. フレームワーク グループが存在しない場合は、プロジェクト グループにフレームワーク グループを作成します。 すでにあります。

    4. Consumer SDK をインストールするには、[Frameworks, Libraries, and Embedded Content] の下のプロジェクトに GoogleRidesharingConsumer.xcframework ファイルをドラッグします。プロンプトが表示されたら、必要に応じて [Copy items] を選択します。

    5. ダウンロードした GoogleRidesharingConsumer.bundle を Xcode プロジェクトの最上位ディレクトリにドラッグします。プロンプトが表示されたら、[Copy items if needed] を選択します。

    6. プロジェクト ナビゲータでプロジェクトを選択し、 通信できます。

    7. [Build Phases] タブを開き、[Link Binary with Libraries] に、 次のフレームワークとライブラリがまだ存在しない場合は、

      • 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
    8. 特定のターゲットではなくプロジェクトを選択して、[Build 設定タブ。[Other Linker Flags] セクションで、次のリンクに -ObjC を追加します。 デバッグとリリースの両方に対応しています。これらの設定が表示されない場合は、 Build 設定バーで [Basic] から [All] にフィルタします。

    Apple Privacy Manifest ファイルを調べる

    Apple が App Store のアプリについては、アプリのプライバシーに関する詳細情報を必要とします。最新情報などについては、Apple App Store のプライバシーの詳細ページをご覧ください。

    Apple Privacy Manifest ファイルは、SDK のリソース バンドルに含まれています。プライバシー マニフェスト ファイルが含まれていることを確認し、その内容を検査するには、アプリのアーカイブを作成し、そのアーカイブからプライバシー レポートを生成します。

    アプリケーションの統合

    認証トークンを指定する

    ユーザー アプリが Fleet Engine にルート更新情報をリクエストすると、 有効なアクセス トークンを含める必要があります。これらのリクエストを承認して認証するには、 Consumer SDK は API 定義に従ったオブジェクトを GMTCAuthorization プロトコル。オブジェクトは、 アクセス トークンを取得します。

    トークンの生成方法は、アプリ デベロッパーが選択します。お客様の実装 次の機能を提供する必要があります。

    • HTTPS サーバーからアクセス トークン(JSON 形式など)をフェッチします。
    • トークンを解析してキャッシュに保存します。
    • 期限切れになったらトークンを更新します。

    Fleet Engine サーバーによって予期されるトークンの詳細については、 JSON Web Token(JWT)を 承認します

    プロバイダ ID は Google Cloud プロジェクト ID と同じです。詳しくは フリートのスタートガイドをご覧ください。 Engine です。

    次の例では、アクセス トークン プロバイダを実装しています。

    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
    

    アプリケーションの初期化

    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
    

    マップビューの統合

    マップビューを初期化する

    次の例は、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
    

    マップビュー イベントを処理する

    次の例は、デリゲートを実装してお客様の状態を処理する方法を示しています。 できます。

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

    移動経路の共有

    ビューが読み込まれたときに新しいルートを開始する

    次の例は、ジャーニーの直後にジャーニーの共有を開始する方法を示しています。 ビューが読み込まれます。降車場所や乗車場所などのすべてのユーザー入力を収集できる ViewController から作成したうえで、新しい ViewController を作成して 共有できるようになりました。

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

    実施中のルートをキャンセルする

    次の例は、現在アクティブなルートをリセットする方法を示しています。

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

    ルート更新情報を聞く

    次の例は、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];
      ...
    }
    

    次の例は、tripModel の登録をキャンセルする方法を示しています。 呼び出すことができます。

    Swift

    /*
    
        *   MapViewController.swift
     */
    deinit {
      self.currentTripModel.unregisterSubscriber(self)
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    -   (void)dealloc {
      [self.currentTripModel unregisterSubscriber:self];
      ...
    }
    

    次の例は、GMTCTripModelSubscriber を実装する方法を示しています。 ルート状態が更新されたときにコールバックを処理するためのプロトコルです。

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

    エラー処理

    tripModel を登録したときにエラーが発生した場合は デリゲート メソッドを実装して tripModel tripModel(_:didFailUpdateTripWithError:)。Fleet Engine がエラーが発生した エラー メッセージが返されます。詳細エラーの場合 メッセージ定義とすべてのエラーコードは、Google Cloud エラー ドキュメントをご覧ください

    具体的には、ルート監視の場合、有効な認証情報を提供する必要があります。 あります。有効な認証がない場合、401 UNAUTHENTICATED が発生します。 認証情報(トークンの期限切れなど)が渡されます。トークンが期限切れになった場合は、403 PERMISSION_DENIED が 呼び出し元に特定の API を呼び出す権限がない(コンシューマ ロールが updateTrip を呼び出そうとした場合)、またはリクエストに有効な vehicle_id/trip_id がありません。 指定することもできます。

    詳しくは、Consumer SDK Error(コンシューマ SDK エラー)をご覧ください。 取り扱いをご覧ください。

    UI のカスタマイズ

    カスタム ポリラインの UI オプションを取得して設定する

    次の例は、ポリラインのカスタム UI オプションを設定する方法を示しています。

    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 オプションを取得、設定する

    次の例は、マーカーのカスタム UI オプションを設定する方法を示しています。

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

    カメラのズームの調整

    現在地 ボタン では、デバイスの位置にカメラの中心を合わせます。

    アクティブな移動経路の共有セッションがある場合は、カメラの中心を デバイスの位置情報だけでなく、カスタマー ジャーニーに集中できます。

    Consumer SDK には自動カメラ機能が備わっており、 デフォルトで有効になっています。移動経路の共有経路にピントが合わせ、カメラがズームします。 表示されます。

    AutoCamera

    カメラの動作をより細かく制御する必要がある場合は、 自動カメラ機能を使用するには、 isAllowCameraAutoUpdate プロパティです。

    カメラの詳細なカスタマイズについては、Maps SDK for iOS: カメラ