このガイドでは、Navigation SDK for iOS を使用して、アプリ内で単一の目的地までのルートをプロットする方法について説明します。
概要
- プロジェクトを設定するセクションの説明に沿って、Navigation SDK をアプリに統合します。
 GMSMapViewを構成します。- 利用規約に同意し、位置情報サービスとバックグラウンド通知を承認するようユーザーに促します。
 - 1 つ以上のデスティネーションを含む配列を作成します。
 GMSNavigatorを定義して、ターンバイターン方式のナビゲーションを制御します。setDestinationsを使用してデスティネーションを追加します。isGuidanceActiveをtrueに設定して、ナビを開始します。simulateLocationsAlongExistingRouteを使用して、テスト、デバッグ、アプリのデモのために、ルートに沿った車両の進行状況をシミュレートします。
コードの確認
必要な承認をユーザーに求める
Navigation SDK を使用する前に、ユーザーは利用規約に同意し、ナビゲーションに必要な位置情報サービスの利用を承認する必要があります。アプリがバックグラウンドで実行される場合は、ガイダンス アラート通知を承認するようユーザーに求める必要があります。このセクションでは、必要な承認プロンプトを表示する方法について説明します。
位置情報サービスを承認する
Navigation SDK は位置情報サービスを使用するため、ユーザーの承認が必要です。位置情報サービスを有効にして承認ダイアログを表示するには、次の手順を行います。
NSLocationAlwaysUsageDescriptionキーをInfo.plistに追加します。値には、アプリで位置情報サービスが必要な理由を簡単に説明します。例: 「このアプリは、ターンバイターン ナビゲーションに位置情報サービスを使用するための権限を必要としています。」
承認ダイアログを表示するには、位置情報マネージャー インスタンスの
requestAlwaysAuthorization()を呼び出します。
Swift
self.locationManager.requestAlwaysAuthorization()
Objective-C
[_locationManager requestAlwaysAuthorization];
バックグラウンド ガイダンスのアラート通知を承認する
Navigation SDK は、アプリがバックグラウンドで実行されているときにアラート通知を提供するために、ユーザーの権限を必要とします。次のコードを追加して、これらの通知を表示する権限をユーザーに求めるようにします。
Swift
UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) {
  granted, error in
    // Handle denied authorization to display notifications.
    if !granted || error != nil {
      print("User rejected request to display notifications.")
    }
}
Objective-C
// Request authorization for alert notifications.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions options = UNAuthorizationOptionAlert;
[center requestAuthorizationWithOptions:options
                      completionHandler:
 ^(
   BOOL granted,
   NSError *_Nullable error) {
     if (!error && granted) {
       NSLog(@"iOS Notification Permission: newly Granted");
     } else {
       NSLog(@"iOS Notification Permission: Failed or Denied");
     }
   }];
利用規約に同意します。
次のコードを使用して、利用規約のダイアログを表示し、ユーザーが規約に同意したときにナビゲーションを有効にします。この例には、位置情報サービスとガイダンス アラート通知のコードが含まれています(前述)。
Swift
  let termsAndConditionsOptions = GMSNavigationTermsAndConditionsOptions(companyName: "Ride Sharing Co.")
  GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(
    with: termsAndConditionsOptions) { termsAccepted in
    if termsAccepted {
      // Enable navigation if the user accepts the terms.
      self.mapView.isNavigationEnabled = true
      self.mapView.settings.compassButton = true
      // Request authorization to use location services.
      self.locationManager.requestAlwaysAuthorization()
      // Request authorization for alert notifications which deliver guidance instructions
      // in the background.
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) {
      granted, error in
        // Handle rejection of notification authorization.
        if !granted || error != nil {
          print("Authorization to deliver notifications was rejected.")
        }
      }
    } else {
      // Handle rejection of terms and conditions.
    }
  }
Objective-C
GMSNavigationTermsAndConditionsOptions *termsAndConditionsOptions = [[GMSNavigationTermsAndConditionsOptions alloc] initWithCompanyName:@"Ride Sharing Co."];
[GMSNavigationServices
  showTermsAndConditionsDialogIfNeededWithOptions:termsAndConditionsOptions
  callback:^(BOOL termsAccepted) {
   if (termsAccepted) {
     // Enable navigation if the user accepts the terms.
     _mapView.navigationEnabled = YES;
     _mapView.settings.compassButton = YES;
     // Request authorization to use the current device location.
     [_locationManager requestAlwaysAuthorization];
     // Request authorization for alert notifications which deliver guidance instructions
     // in the background.
     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
     UNAuthorizationOptions options = UNAuthorizationOptionAlert;
     [center requestAuthorizationWithOptions:options
                           completionHandler:
     ^(
       BOOL granted,
       NSError *_Nullable error) {
         if (!error && granted) {
           NSLog(@"iOS Notification Permission: newly Granted");
         } else {
           NSLog(@"iOS Notification Permission: Failed or Denied");
         }
       }];
   } else {
     // Handle rejection of the terms and conditions.
   }
 }];
ルートを作成してガイダンスを開始する
ルートをプロットするには、1 つ以上の訪問先(GMSNavigationWaypoint)を含む配列を指定して、ナビゲーターの setDestinations() メソッドを呼び出します。計算が正常に完了すると、地図上に経路が表示されます。最初の目的地からルートに沿ったガイダンスを開始するには、コールバックで isGuidanceActive を true に設定します。
次の例は、以下の条件に従って表示します。
- 2 つの目的地を含む新しいルートを作成する。
 - ガイダンスを開始します。
 - バックグラウンド ガイダンス通知を有効にする。
 - ルートに沿った移動をシミュレートする(省略可)。
 - カメラモードを [追跡] に設定する(省略可)。
 
Swift
func startNav() {
  var destinations = [GMSNavigationWaypoint]()
  destinations.append(GMSNavigationWaypoint.init(placeID: "ChIJnUYTpNASkFQR_gSty5kyoUk",
                                                 title: "PCC Natural Market")!)
  destinations.append(GMSNavigationWaypoint.init(placeID:"ChIJJ326ROcSkFQRBfUzOL2DSbo",
                                                 title:"Marina Park")!)
  mapView.navigator?.setDestinations(destinations) { routeStatus in
    self.mapView.navigator?.isGuidanceActive = true
    self.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()
    self.mapView.cameraMode = .following
  }
}
Objective-C
- (void)startNav {
  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){
                               [_mapView.locationSimulator simulateLocationsAlongExistingRoute];
                               _mapView.navigator.guidanceActive = YES;
                               _mapView.cameraMode = GMSNavigationCameraModeFollowing;
                             }];
}
プレイス ID について詳しくは、プレイス ID をご覧ください。
マルチストップ シナリオ
setDestinations メソッドは、複数経由地の旅程をサポートしていません。continueToNextDestination() を使用して、ウェイポイントを次の旅程に進めます。
移動手段を設定する
移動手段は、取得するルートの種類と、ユーザーのコースを決定する方法を決定します。ルートには、車、自転車、徒歩、タクシーの 4 つの移動手段のいずれかを設定できます。運転モードとタクシーモードでは、ユーザーのコースは移動方向に基づきます。サイクリング モードとウォーキング モードでは、コースはデバイスの向き(横向きモードではデバイスの上部)で表されます。
次の例に示すように、地図ビューの travelMode プロパティを設定します。
Swift
self.mapView.travelMode = .cycling
Objective-C
_mapView.travelMode = GMSNavigationTravelModeCycling;
回避する道路を設定する
avoidsHighways プロパティと avoidsTolls BOOL プロパティを使用して、ルート上の高速道路や有料道路を回避します。
Swift
self.mapView.navigator?.avoidsTolls = true
Objective-C
_mapView.navigator.avoidsTolls = YES;
PlaceID 検索ツール
PlaceID Finder を使用して、ルートの目的地に使用するプレイス ID を見つけることができます。GMSNavigationWaypoint を含む placeID からデスティネーションを追加します。
フローティング テキスト
Google の帰属表示が隠れない限り、アプリの任意の場所にフローティング テキストを追加できます。Navigation SDK は、地図上の緯度/経度またはラベルにテキストを固定することをサポートしていません。詳細については、情報ウィンドウをご覧ください。