瀏覽路線

請按照本指南的說明,使用 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.
   }
 }];

建立路徑並開始導航

如要繪製路線,請使用包含一或多個目的地 (GMSNavigationWaypoint) 的陣列呼叫導覽器的 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;

PlaceID 搜尋器

您可以使用 PlaceID Finder 來尋找用於路線目的地的地點 ID。使用 GMSNavigationWaypointplaceID 新增目的地。

浮動文字

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