ルートを移動する

このガイドでは、Navigation SDK for iOS を使用して、アプリ内で 1 つの目的地までのルートをプロットする方法について説明します。

概要

  1. プロジェクトを設定するの説明に従って、Navigation SDK をアプリに統合します。
  2. GMSMapView を構成します。
  3. 利用規約に同意し、位置情報サービスとバックグラウンド通知を承認するようユーザーに求めます。
  4. 1 つ以上の目的地を含む配列を作成します。
  5. ターンバイターン方式ナビを制御する GMSNavigator を定義します。

    • setDestinations を使用して目的地を追加します。
    • isGuidanceActivetrue に設定してナビゲーションを開始します。
    • simulateLocationsAlongExistingRoute を使用して、アプリのテスト、 デバッグ、デモのために、ルートに沿った車両の進行状況をシミュレートします。

コードの確認

必要な承認をユーザーに求める

Navigation SDK を使用する前に、ユーザーは利用規約に同意し、ナビゲーションに必要な位置情報サービスの使用を承認する必要があります。アプリがバックグラウンドで実行される場合は、ガイダンス アラート通知を承認するようユーザーに求める必要もあります。このセクションでは、必要な承認プロンプトを表示する方法について説明します。

位置情報サービスを承認する

Navigation SDK は位置情報サービスを使用するため、ユーザーの承認が必要です。位置情報サービスを有効にして承認ダイアログを表示する手順は次のとおりです。

  1. NSLocationWhenInUseUsageDescription キーと NSLocationAlwaysAndWhenInUseUsage キーを Info.plist に追加します。
  2. 値として、アプリが位置情報サービスを必要とする理由を簡単に説明します。例: 「このアプリは、ターンバイターン方式のナビに位置情報サービスを使用する権限が必要です。」

  3. 承認ダイアログを表示するには、ロケーション マネージャー インスタンスの requestAlwaysAuthorization() メソッドを呼び出します。

Swift

self.locationManager.requestAlwaysAuthorization()

Objective-C

[_locationManager requestAlwaysAuthorization];

位置情報サービスの承認に関する Apple のドキュメント全文をご覧ください

バックグラウンド ガイダンスのアラート通知を承認する

アプリがバックグラウンドで実行されているときにアラート通知を提供するには、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.
   }
 }];

ルートを作成してガイダンスを開始する

ルートをプロットするには、ナビゲーターの setDestinations() メソッドを呼び出し、1 つ以上の目的地 (GMSNavigationWaypoint) の配列を渡します。正常に計算されると、ルートが地図上に表示されます。ルートに沿ってガイダンスを開始するには、コールバックで isGuidanceActivetrue に設定します。

次の例は、以下の条件に従って表示します。

  • 1 つの目的地を含む新しいルートを作成する。
  • ガイダンスを開始する。
  • バックグラウンド ガイダンス通知を有効にする。
  • ルートに沿った移動をシミュレートする(省略可)。
  • カメラモードを [追従] に設定する(省略可)。

Swift

func startNav() {
  var destinations = [GMSNavigationWaypoint]()
  destinations.append(GMSNavigationWaypoint.init(placeID: "ChIJnUYTpNASkFQR_gSty5kyoUk",
                                                 title: "PCC Natural Market")!)

  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"],

  [_mapView.navigator setDestinations:destinations
                             callback:^(GMSRouteStatus routeStatus){
                               [_mapView.locationSimulator simulateLocationsAlongExistingRoute];
                               _mapView.navigator.guidanceActive = YES;
                               _mapView.cameraMode = GMSNavigationCameraModeFollowing;
                             }];
}

プレイス ID について詳しくは、プレイス ID をご覧ください。

複数の経由地があるシナリオ

最大 25 個の経由地を構成できます。

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;

Place ID Finder

Place ID Finder を使用して、ルートの目的地に使用するプレイス ID を見つけることができます。GMSNavigationWaypoint を使用して、placeID から目的地を追加します。

フローティング テキスト

Google の帰属表示が覆われていない限り、アプリの任意の場所にフローティング テキストを追加できます。Navigation SDK では、地図上の緯度/経度やラベルにテキストを固定することはできません。詳しくは、 情報ウィンドウをご覧ください。