瀏覽路線

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

總覽

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

查看程式碼

提示使用者提供必要授權

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

授權定位服務

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

  1. NSLocationAlwaysUsageDescription 鍵新增至 Info.plist
  2. 請在值中簡短說明應用程式需要位置資訊服務的原因。例如:「這款應用程式需要位置資訊服務權限,才能提供逐步導航功能。」

  3. 如要顯示授權對話方塊,請呼叫位置管理工具執行個體的 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.
   }
 }];

建立路線並開始導航

如要規劃路線,請使用包含一或多個目的地 (GMSNavigationWaypoint) 的陣列呼叫 Navigator 的 setDestinations() 方法。如果計算成功,地圖上會顯示路線。如要開始沿路線導覽,請在回呼中將 isGuidanceActive 設為 true,從第一個目的地開始。

在下列範例中:

  • 建立含有兩個目的地的新路線。
  • 入門指引。
  • 啟用背景指引通知。
  • 模擬沿路線的行程 (選用)。
  • 將攝影機模式設為「追蹤」(選用)。

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」。

設定交通方式

系統會根據交通方式擷取路徑類型,並決定使用者路線的判斷方式。你可以為路線設定四種交通方式之一:開車、騎單車、步行和搭計程車。在「開車」和「搭計程車」模式中,使用者路線會根據行進方向顯示;在「騎自行車」和「步行」模式中,路線會根據裝置面向的方向顯示 (在橫向模式中,路線會朝向裝置頂端)。

設定地圖檢視區塊的 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。從具有 GMSNavigationWaypointplaceID 新增目的地。

浮動文字

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