浏览路线

按照本指南使用 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 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 不支持将文本锚定到地图上的纬度/经度,或锚定到标签上。如需了解详情,请参阅信息窗口