瀏覽路線

請按照本指南操作,使用 Navigation SDK for iOS 在應用程式中規劃前往單一目的地的路線。

總覽

  1. 按照「設定專案」一節的說明,將 Navigation SDK 整合至應用程式。
  2. 設定 GMSMapView
  3. 提示使用者接受條款及細則,並授權位置資訊服務和背景通知。
  4. 建立包含一或多個目的地的陣列。
  5. 定義 GMSNavigator,控制即時路況導航。

查看程式碼

提示使用者授予必要授權

使用者必須先同意條款及細則,並授權使用位置資訊服務 (導航功能需要這項服務),才能使用 Navigation SDK。如果應用程式會在背景執行,也必須提示使用者授權接收引導警示通知。本節說明如何顯示必要的授權提示。

授權定位服務

Navigation SDK 會使用定位服務,因此需要使用者授權。如要啟用定位服務並顯示授權對話方塊,請按照下列步驟操作:

  1. 在 Xcode 中啟用位置資訊和背景功能:

    1. 在 Xcode 中開啟目標,然後選取「Signing & Capabilities」分頁。詳情請參閱 Apple 的應用程式功能新增指南
    2. 新增「位置資訊 (一律允許)」和「位置資訊 (使用應用程式時)」功能。在每個文字欄位中,簡要說明應用程式需要位置資訊服務的原因 (例如:「這個應用程式需要位置資訊服務的使用權限,才能提供逐步導航功能。」)。
    3. 新增「Background Modes」功能,然後勾選「Location updates」核取方塊。如果沒有這項功能,應用程式會在啟動導航時停止運作。詳情請參閱 Apple 的指南,瞭解如何處理背景位置資訊更新。
  2. 如要顯示授權對話方塊,請呼叫位置管理工具例項的 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.
   }
 }];

建立路線並開始導航

如要繪製路線,請使用一或多個要造訪的 GMSNavigationWaypoint 目的地陣列,呼叫導覽器的 setDestinations 方法。如果成功計算路徑,地圖上就會顯示路徑。如要開始沿路線提供指引,請在回呼中將 isGuidanceActive 設為 true

在下列範例中:

  • 建立新路線,並設定一個目的地。
  • 入門指引。
  • 啟用背景指引通知。
  • 模擬沿途的旅行 (選用)。
  • 將攝影機模式設為「追蹤」(選用)。

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 方法不支援多個停靠點的行程。使用 continueToNextDestinationWithCompletion() 將航點移至旅程的下一段。

設定交通方式

交通方式會定義要擷取的路線類型,以及如何判斷使用者的路線。你可以為路線設定四種交通方式: 開車、騎單車、步行和搭計程車。在開車和計程車模式中,使用者路線會根據行進方向而定;在自行車和步行模式中,路線會以裝置面向的方向表示 (在橫向模式中,路線會朝向裝置頂端)。

設定地圖檢視區塊的 travelMode 屬性,如以下範例所示:

Swift

self.mapView.travelMode = .cycling

Objective-C

_mapView.travelMode = GMSNavigationTravelModeCycling;

設定要避開的道路

使用 avoidsHighwaysavoidsTolls BOOL 屬性,避開路線上的高速公路、收費道路或兩者。

Swift

self.mapView.navigator?.avoidsTolls = true

Objective-C

_mapView.navigator.avoidsTolls = YES;

地點 ID 搜尋器

您可以使用地點 ID 查詢工具,找出可用於路線目的地的地點 ID。從 placeID 新增目的地 (使用 GMSNavigationWaypoint)。

浮動文字

只要不遮蓋 Google 署名資訊,您可以在應用程式的任何位置新增浮動文字。Navigation SDK 不支援將文字錨定至地圖上的特定座標 (經緯度) 或標籤。詳情請參閱資訊視窗