Follow this guide to plot a route within your app to a single destination,
using the Navigation SDK for iOS.

## Overview

1. Integrate the Navigation SDK into your app, as described in the [Set up your project](https://developers.google.com/maps/documentation/navigation/ios-sdk/config) section.
2. Configure a [`GMSMapView`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSMapView.md.txt).
3. Prompt the user to accept the terms and conditions, and authorize location services and background notifications.
4. Create an array containing one or more destinations.
5. Define a [`GMSNavigator`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSNavigator.md.txt)
   to control turn-by-turn navigation.

   - Add destinations using [`setDestinations`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSNavigator.md.txt#-setdestinations:callback:).
   - Set [`isGuidanceActive`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSNavigator.md.txt#guidanceactive) to `true` to start navigation.
   - Use [`simulateLocationsAlongExistingRoute`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSLocationSimulator.md.txt#-simulatelocationsalongexistingroute) to simulate the progress of the vehicle along the route, for testing, debugging, and demonstrating your app.

> [!NOTE]
> **Note:** To prevent the screen from dimming or turning off while navigating, your app must [disable the idle timer](https://developer.apple.com/documentation/uikit/uiapplication/1623070-idletimerdisabled), as the Navigation SDK doesn't do this for you. To disable the idle timer, make the following call:   
> `[UIApplication sharedApplication].idleTimerDisabled = YES;`.

## See the code

Show/Hide the Swift code
for the navigation view controller.

```
/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import GoogleNavigation
import UIKit

class ViewController: UIViewController {

  var mapView: GMSMapView!
  var locationManager: CLLocationManager!

  override func loadView() {

    locationManager = CLLocationManager()

    // Set up the map view.
    let camera = GMSCameraPosition.camera(withLatitude: 47.67, longitude: -122.20, zoom: 14)
    mapView = GMSMapView.map(withFrame: .zero, camera: camera)

    // Show the terms and conditions.
    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 denied authorization to display notifications.
          if !granted || error != nil {
            print("User rejected request to display notifications.")
          }
        }
      } else {
        // Handle rejection of terms and conditions.
      }
    }

    view = mapView

    makeButton()
  }

  // Create a route and start guidance.
  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
      guard routeStatus == .OK else {
        print("Handle route statuses that are not OK.")
        return
      }
      self.mapView.navigator?.isGuidanceActive = true
      self.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()
      self.mapView.cameraMode = .following
    }
  }

  // Add a button to the view.
  func makeButton() {
    // A button to start navigation.
    let navButton = UIButton(frame: CGRect(x: 5, y: 150, width: 200, height: 35))
    navButton.backgroundColor = .blue
    navButton.alpha = 0.5
    navButton.setTitle("Start navigation", for: .normal)
    navButton.addTarget(self, action: #selector(startNav), for: .touchUpInside)
    self.mapView.addSubview(navButton)
  }

}
```
Show/Hide the Objective-C code for the navigation view controller.

```
/*
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "ViewController.h"
@import GoogleNavigation;

@interface ViewController ()
@end

@implementation ViewController {
  GMSMapView *_mapView;
  CLLocationManager *_locationManager;
}

- (void)loadView {

  _locationManager = [[CLLocationManager alloc] init];

  // Set up the map view.
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:47.67
                                                          longitude:-122.20
                                                               zoom:14];
  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

  // Show the terms and conditions.
  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.
     }
   }];

  self.view = _mapView;

  [self makeButton];
}

// Create a route and initiate navigation.
- (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.navigator.sendsBackgroundNotifications = YES;
                               _mapView.cameraMode = GMSNavigationCameraModeFollowing;
                             }];
}

// Add a button to the view.
- (void)makeButton {
  // A button to start navigation.
  UIButton *navButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [navButton addTarget:self
                action:@selector(startNav)
      forControlEvents:UIControlEventTouchUpInside];
  [navButton setTitle:@"Navigate" forState:UIControlStateNormal];
  [navButton setBackgroundColor:[UIColor blueColor]];
  navButton.frame = CGRectMake(5.0, 150.0, 100.0, 35.0);
  [_mapView addSubview:navButton];
}

@end
```

## Prompt the user for the necessary authorizations

Before using the Navigation SDK, the user must agree to the
terms and conditions, and authorize the use of location services, which is
required for navigation. If your app will run in the background, it must also
prompt the user to authorize guidance alert notifications. This section shows
how to display the required authorization prompts.

### Authorize location services

The Navigation SDK uses location services, which requires
user authorization. To enable location services and display the authorization
dialog, take these steps:

1. Enable the location and background capabilities in Xcode:

   1. Open your target in Xcode and select the **Signing \&
      Capabilities** tab. For details, see Apple's guide on [adding capabilities to your app](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app).
   2. Add the **Location (Always)** and **Location (When In Use)** capabilities. In the text field for each, add a short explanation of why your app requires location services (for example: "This app needs permission to use location services for turn-by-turn navigation.").
   3. Add the **Background Modes** capability, and then select the **Location
      updates** checkbox. Without this capability, the app crashes when starting navigation. For details, see Apple's guide on [handling location updates in the background](https://developer.apple.com/documentation/corelocation/handling-location-updates-in-the-background).
2. To display the authorization dialog, call the
   [`requestAlwaysAuthorization()`](https://developer.apple.com/documentation/corelocation/cllocationmanager/requestalwaysauthorization())
   method of the location manager instance.

<br />

### Swift

<br />

```swift
self.locationManager.requestAlwaysAuthorization()
```

<br />

### Objective-C

<br />

```objective-c
[_locationManager requestAlwaysAuthorization];
```

<br />

<br />

[See the full Apple documentation for location service authorization](https://developer.apple.com/documentation/corelocation/requesting-authorization-to-use-location-services).

### Authorize alert notifications for background guidance

The Navigation SDK needs user permission to provide alert
notifications when the app is running in the background. Add the following code
to prompt the user for permission to display these notifications:

<br />

### Swift

<br />

```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.")
    }
}
```

<br />

### Objective-C

<br />

```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");
     }
   }];
```

<br />

<br />

### Authorize motion sensors

> [!IMPORTANT]
> **Important:** To prevent app crashes in a future major release (version 11.0.0 and later), add the `NSMotionUsageDescription` key to your app's `Info.plist` now.

In a future major release, the Navigation SDK for iOS combines core location data with
device motion sensors (`CMAltimeter`) to calculate routing altitude. When the
SDK accesses the altimeter, iOS automatically uses this string to prompt the
user for permission.

Adding this key now has no impact on current behavior but prevents
initialization crashes when you upgrade the SDK later.

To prepare for future upgrades of the SDK, configure the motion sensor
authorizations as follows:

1. Open your target in Xcode and navigate to the **Info** tab, or open your
   `Info.plist` file.

2. Add a new key: **Privacy - Motion Usage Description**
   (`NSMotionUsageDescription`).

3. Add a short explanation for the user. For example: "This app requires motion
   sensor access to calculate altitude and improve map routing accuracy."

### Accept the terms and conditions

Use the following code to show the terms and conditions dialog, and enable
navigation when the user accepts the terms. Note that this example includes
the code for location services and guidance alert notifications (shown
previously).

<br />

### Swift

<br />

```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.
    }
  }
```

<br />

### Objective-C

<br />

```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.
   }
 }];
```

<br />

<br />

## Create a route and start guidance

To plot a route, call the navigator's `setDestinations` method with an array of
one or more
[`GMSNavigationWaypoint`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSNavigationWaypoint.md.txt)
destinations to visit. If the route is successfully computed, it appears on the
map. To start guidance along the route, set `isGuidanceActive` to `true` in the
callback.

The following example shows:

- Creating a new route with one destination.
- Starting guidance.
- Enabling background guidance notifications.
- Simulating travel along the route (optional).
- Setting the camera mode to "follow" (optional).

<br />

### Swift

<br />

```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
  }
}
```

<br />

### Objective-C

<br />

```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;
                             }];
}
```

<br />

<br />

To learn about Place IDs, refer to [Place IDs](https://developers.google.com/maps/documentation/places/web-service/place-id.md.txt).

### Multi-stop scenarios

You can configure a maximum of 25 waypoints.

The Navigation SDK doesn't automatically advance to the next
destination. When the vehicle arrives at a waypoint, call
[`continueToNextDestinationWithCompletion:`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSNavigator.md.txt#-continuetonextdestinationwithcompletion:)
to start the next leg of the trip. This also applies to route tokens that have
intermediate waypoints. When you advance to the next destination, the
Navigation SDK keeps following the route from your route token
instead of planning a new route.

> [!CAUTION]
> **Caution:** Calling the `continueToNextDestinationWithCompletion:` method can sometimes result in an incorrect arrival event, where the just-completed destination appears to be re-selected.

## Set travel mode

Travel mode defines both the type of route to fetch and how to determine the
user's course. You can set one of four travel modes for a route:
driving, cycling, walking, and taxi. In driving and taxi mode, the user's course
is based on the direction of travel; in cycling and walking mode the course is
represented by the direction the device is facing (toward the top of the device
in landscape mode).

> [!IMPORTANT]
> **Important:** Taxi mode is an experimental feature.

> [!NOTE]
> **Note:** When testing cycling or walking mode with an emulator, neither the chevron direction nor the map orientation appears to change. However, when using a physical device, the map orientation changes when you rotate the device, while the chevron continues to point in the direction that the device is facing.

Set the
[`travelMode`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSMapView.md.txt#/c:objc(cs)GMSMapView(py)travelMode)
property of the map view, as shown in the following example:

<br />

### Swift

<br />

```swift
self.mapView.travelMode = .cycling
```

<br />

### Objective-C

<br />

```objective-c
_mapView.travelMode = GMSNavigationTravelModeCycling;
```

<br />

<br />

## Set roads to avoid

Use the `avoidsHighways` and `avoidsTolls` `BOOL` properties to avoid
highways, toll roads, or both along a route.

<br />

### Swift

<br />

```swift
self.mapView.navigator?.avoidsTolls = true
```

<br />

### Objective-C

<br />

```objective-c
_mapView.navigator.avoidsTolls = YES;
```

<br />

<br />

## Set the audio guidance volume

To adjust the voice guidance volume, set the `volumeLevel` property on the
navigator to low, normal, or high. The navigator uses the last persisted volume
level, or defaults to normal.

<br />

### Swift

<br />

```swift
self.mapView.navigator?.volumeLevel = .low
```

<br />

### Objective-C

<br />

```objective-c
_mapView.navigator.volumeLevel = GMSNavigationVolumeLevelLow;
```

<br />

<br />

## PlaceID finder

You can use the [PlaceID Finder](https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder.md.txt)
to find place IDs to use for route destinations. Add a destination from a
`placeID` with [`GMSNavigationWaypoint`](https://developers.google.com/maps/documentation/navigation/ios-sdk/reference/objc/Classes/GMSNavigationWaypoint.md.txt).

## Floating text

You can add floating text anywhere in your app, as long as the Google
attribution isn't covered. The Navigation SDK doesn't support anchoring the text
to specific coordinates (latitude, longitude) on the map, or to a label. For
more information, see
[Info windows](https://developers.google.com/maps/documentation/ios-sdk/infowindows.md.txt#maps_ios_markers_info_window_title-objective-c).