瀏覽路線

請按照本指南使用 iOS 版 Navigation SDK,將應用程式內的路線規劃至單一目的地。

總覽

  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 companyName = "Ride Sharing Co."
GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(
  withCompanyName: companyName) { 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

NSString *companyName = @"Ride Sharing Co.";
[GMSNavigationServices
  showTermsAndConditionsDialogIfNeededWithCompanyName:companyName
  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() 方法,並利用陣列包含一或多個要造訪的目的地 (GMSNavigationWaypoint)。如果計算成功,地圖就會顯示路線。如要在路線上開始導航,請從第一個目的地開始,請在回呼中將 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 搜尋器

您可以使用 PlaceID Finder 尋找地點 ID,以便用於路線目的地。

浮動文字

您可以在應用程式的任何位置新增浮動文字,前提是 Google 歸因不在涵蓋範圍內。Navigation SDK 不支援將文字錨定在地圖上的經緯度或標籤。詳情請參閱資訊視窗