### Full Navigation Example Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Demonstrates a complete workflow: initializing the navigator, setting the delegate, computing a route, and starting guidance. Includes error handling and weak self for delegate callbacks. ```swift import GoogleNavigation import CoreLocation class MyNavigationController: UIViewController, GMSNavigatorDelegate { let navigator = GMSNavigator() override func viewDidLoad() { super.viewDidLoad() navigator.delegate = self } func findRouteAndNavigate() { let origin = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) let destination = CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437) navigator.computeRoutes( origin: origin, destination: destination, waypoints: nil ) { [weak self] result, error in guard let self = self, let result = result else { print("Error: \(error?.localizedDescription ?? "Unknown")") return } if let route = result.routes.first { self.navigator.startGuidance(for: route) } } } } ``` -------------------------------- ### Initialize and Configure GMSNavigationViewController Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Example of initializing GMSNavigationViewController, setting its delegate, and adding it as a child view controller. Also shows how to start navigation. ```swift import GoogleNavigation class NavigationViewController: UIViewController { var navigationViewController: GMSNavigationViewController? override func viewDidLoad() { super.viewDidLoad() // Initialize navigation view controller navigationViewController = GMSNavigationViewController() // Set delegate to receive navigation events navigationViewController?.delegate = self // Add as child view controller addChild(navigationViewController!) view.addSubview(navigationViewController!.view) navigationViewController!.view.frame = view.bounds navigationViewController!.didMove(toParent: self) } func startNavigationToDestination(routeLeg: GMSRouteLeg, routeToken: String) { navigationViewController?.startGuidance(for: routeLeg, routeToken: routeToken) } } ``` -------------------------------- ### Example Usage of GMSRoutesResult Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md A comprehensive example demonstrating how to handle route results, iterate through options, and initiate navigation with the recommended route. ```swift import GoogleNavigation import CoreLocation func handleRouteResults(result: GMSRoutesResult) { guard !result.routes.isEmpty else { print("No routes available") return } print("Found \(result.routes.count) route option(s)") for (index, route) in result.routes.enumerated() { let distance = route.distanceMeters / 1000 let duration = Int(route.duration) / 60 print("Route \(index + 1): \(distance)km, \(duration) min") } // Use the first (recommended) route if let recommendedRoute = result.routes.first { startNavigation(with: recommendedRoute) } } ``` -------------------------------- ### Example GMSNavigationViewControllerDelegate Implementation Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md An example implementation of the GMSNavigationViewControllerDelegate protocol, demonstrating how to handle navigation updates, cancellations, and notifications. ```swift import GoogleNavigation class MyNavigationDelegate: NSObject, GMSNavigationViewControllerDelegate { func navigationViewController( _ navigationViewController: GMSNavigationViewController, didUpdate navigationUpdates: GMSNavigationUpdates, for routeToken: String ) { print("Distance remaining: \(navigationUpdates.distanceToNextWaypoint) meters") print("Time remaining: \(navigationUpdates.timeToNextWaypoint) seconds") } func navigationViewControllerWasCancelled( _ navigationViewController: GMSNavigationViewController ) { print("User cancelled navigation") } func navigationViewController( _ navigationViewController: GMSNavigationViewController, didReceiveNavigationNotification notification: GMSNavigationNotification ) { print("Navigation notification: \(notification.type)") } } ``` -------------------------------- ### Starting Navigation Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/INDEX.md Methods to begin and end the turn-by-turn navigation guidance. ```APIDOC ## Start/Stop Navigation ### Description Controls the initiation and termination of navigation guidance. ### Methods - **startGuidance(for:)**: Begins navigation for a given route. - **stopGuidance()**: Stops the current navigation session. ``` -------------------------------- ### Example Usage of GMSRouteStep Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Demonstrates how to iterate through route steps and display navigation instructions. ```APIDOC ```swift import GoogleNavigation func displayNavigationInstructions(steps: [GMSRouteStep]) { for (index, step) in steps.enumerated() { print("Step \(index + 1):") print(" Instruction: \(step.instructionText)") print(" Distance: \(step.distanceMeters)m") print(" Maneuver: \(step.maneuverType)") if let road = step.roadName { print(" Road: \(road)") } } } ``` ``` -------------------------------- ### Setup Navigation and Location Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/location-and-camera.md Initializes the GMSNavigationViewController, CLLocationManager, and starts location updates. Requires user authorization for location services. ```swift import UIKit import GoogleNavigation import CoreLocation class NavigationWithCameraViewController: UIViewController, GMSNavigationViewControllerDelegate, CLLocationManagerDelegate { var navigationViewController: GMSNavigationViewController? let navigator = GMSNavigator() let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Setup location locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingHeading() // Setup navigation navigationViewController = GMSNavigationViewController() navigationViewController?.delegate = self addChild(navigationViewController!) view.addSubview(navigationViewController!.view) navigationViewController!.view.frame = view.bounds navigationViewController!.didMove(toParent: self) } // MARK: - Location Updates func locationManager( _ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading ) { // Update camera bearing to match device heading updateCameraBearing(newHeading.trueHeading) } private func updateCameraBearing(_ heading: CLLocationDirection) { guard let navVC = navigationViewController else { return } let position = GMSCameraPosition( target: navVC.currentLocation, zoom: 16.0, bearing: heading, viewingAngle: 45.0 ) navigationViewController?.updateCamera(with: position, animated: false) } // MARK: - Camera Management @IBAction func showRouteOverview() { navigationViewController?.showsRouteOverview = true navigationViewController?.cameraMode = .overview } @IBAction func returnToFollowing() { navigationViewController?.cameraMode = .following navigationViewController?.recenterButtonVisible = true } @IBAction func zoomIn() { let current = navigationViewController?.currentLocation ?? CLLocationCoordinate2D() let position = GMSCameraPosition( target: current, zoom: 19.0, bearing: 0.0, viewingAngle: 30.0 ) navigationViewController?.updateCamera(with: position, animated: true) } @IBAction func zoomOut() { let current = navigationViewController?.currentLocation ?? CLLocationCoordinate2D() let position = GMSCameraPosition( target: current, zoom: 13.0, bearing: 0.0, viewingAngle: 0.0 ) navigationViewController?.updateCamera(with: position, animated: true) } // MARK: - Navigation Delegate func navigationViewController( _ navigationViewController: GMSNavigationViewController, didUpdate navigationUpdates: GMSNavigationUpdates, for routeToken: String ) { // Could update camera based on navigation progress let nextStep = navigationUpdates.nextStep let distanceToTurn = navigationUpdates.distanceToNextStep // Keep camera following when less than 100m to turn if distanceToTurn < 100 { navigationViewController.cameraMode = .following } } } ``` -------------------------------- ### GMSNavigator.startGuidance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/MANIFEST.txt Starts turn-by-turn navigation for a given route. ```APIDOC ## GMSNavigator.startGuidance(for:) ### Description Starts turn-by-turn navigation for a given route. ### Method - (void)startGuidanceForRoute:(GMSRoute *)route; ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Start Navigation Guidance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Starts navigation guidance for a specific route. This method may throw an error if the route is invalid or navigation is already in progress. ```APIDOC ### Navigation Control **method: startGuidance(for:)** Starts navigation guidance for a specific route. ```swift func startGuidance(for route: GMSRoute) ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | for | GMSRoute | Yes | The route to navigate | **Throws:** May throw if the route is invalid or navigation is already in progress. ``` -------------------------------- ### GMSRouteWaypoint Example Usage Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Example of how to create and use GMSRouteWaypoint objects for defining a route. ```APIDOC ## GMSRouteWaypoint Example Usage ### Description Example of how to create and use GMSRouteWaypoint objects for defining a route. ### Code Example ```swift import GoogleNavigation import CoreLocation func createWaypoints() -> [GMSRouteWaypoint] { let startWaypoint = GMSRouteWaypoint( coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), title: "San Francisco" ) let midWaypoint = GMSRouteWaypoint( coordinate: CLLocationCoordinate2D(latitude: 36.7783, longitude: -119.4179), title: "Fresno" ) let endWaypoint = GMSRouteWaypoint( coordinate: CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437), title: "Los Angeles" ) return [startWaypoint, midWaypoint, endWaypoint] } ``` ``` -------------------------------- ### Start and Stop Navigation Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/INDEX.md Initiate navigation for a given route or terminate the current guidance session. ```swift navigator.startGuidance(for:) ``` ```swift navigator.stopGuidance() ``` -------------------------------- ### Start Navigation Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/README.md Initiates turn-by-turn navigation for a given route. Ensure a route object is available before calling this method. ```swift navigator.startGuidance(for: route) ``` -------------------------------- ### Safely Starting Navigation Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/errors.md Implement a function to safely start navigation by first stopping any ongoing or paused navigation sessions. This prevents the 'Navigation Already in Progress' error. ```swift func safeStartNavigation(with route: GMSRoute) { if navigator.navigationState == .enroute || navigator.navigationState == .paused { navigator.stopGuidance() } navigator.startGuidance(for: route) } ``` -------------------------------- ### Initialize GMSNavigator Instance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Creates a new navigator instance. This is the starting point for all navigation-related operations. ```swift let navigator = GMSNavigator() ``` -------------------------------- ### Example: Dynamic Route Overview Display Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/map-display.md Shows the route overview for a set duration, then switches to focus on the current location. ```swift // Show route overview for first 5 seconds navigationViewController.showsRouteOverview = true DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { navigationViewController.showsRouteOverview = false // Now focus on current location } ``` -------------------------------- ### Checking Navigation State Before Starting Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/errors.md Before starting navigation, check the navigator's current state to prevent errors. If navigation is already active or paused, it should be stopped before starting a new route. ```swift if navigator.navigationState == .enroute { // Navigation already active print("Navigation already in progress") } else { navigator.startGuidance(for: route) } ``` -------------------------------- ### Access Leg Start Location Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Get the geographic coordinate where a route leg begins. ```swift let start = leg.startLocation ``` -------------------------------- ### Example: Recenter Button in Overview Mode Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/map-display.md Demonstrates how to set the camera mode to overview and make the recenter button visible, allowing users to return to following mode. ```swift @IBAction func switchToOverviewMode() { navigationViewController.cameraMode = .overview navigationViewController.recenterButtonVisible = true // User can now see recenter button to return to following mode } ``` -------------------------------- ### GMSNavigator.navigationState Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/MANIFEST.txt Gets the current navigation state. ```APIDOC ## GMSNavigator.navigationState (property) ### Description Gets the current navigation state. ### Method @property (nonatomic, assign, readonly) GMSNavigationState navigationState; ### Parameters None ### Request Example None ### Response #### Success Response (200) - **navigationState** (GMSNavigationState) - The current navigation state. #### Response Example None ``` -------------------------------- ### Start Navigation Guidance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Initiates navigation guidance for a given GMSRoute. Ensure the route is valid and navigation is not already in progress to avoid errors. ```swift func startGuidance(for route: GMSRoute) ``` -------------------------------- ### Get Instruction Text Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Retrieves the human-readable instruction for a navigation step. Use this to display navigation guidance to the user. ```swift let instruction = step.instructionText // Example: "Turn left onto Market Street" ``` -------------------------------- ### Start Turn-by-Turn Guidance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Initiates turn-by-turn guidance for a specific route leg using a route token. May throw errors if the route is invalid. ```swift func startGuidance(for: GMSRouteLeg, routeToken: String) ``` -------------------------------- ### Complete Custom Map Display Configuration Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/map-display.md Set up a custom map display by configuring traffic, incidents, safety features, map controls, route display, and camera settings. This example also demonstrates adding custom markers with color-coding. ```swift import UIKit import GoogleNavigation import GoogleMaps class CustomMapDisplayViewController: UIViewController, GMSNavigationViewControllerDelegate { let navigationViewController = GMSNavigationViewController() override func viewDidLoad() { super.viewDidLoad() setupNavigationView() configureMapDisplay() addCustomMarkers() } private func setupNavigationView() { navigationViewController.delegate = self addChild(navigationViewController) view.addSubview(navigationViewController.view) navigationViewController.view.frame = view.bounds navigationViewController.didMove(toParent: self) } private func configureMapDisplay() { // Traffic and incidents navigationViewController.showsTrafficLayer = true navigationViewController.showsIncidentsLayer = true // Safety features navigationViewController.displaySpeedLimitAlert = true // Map controls navigationViewController.showsCompass = true navigationViewController.showsMyLocation = true navigationViewController.showsZoomControls = true // Route display navigationViewController.showsRouteOverview = true // Camera settings navigationViewController.cameraMode = .following navigationViewController.recenterButtonVisible = false } private func addCustomMarkers() { // Add waypoint markers let waypoints = [ CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), CLLocationCoordinate2D(latitude: 37.3382, longitude: -121.8863), CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437) ] for (index, waypoint) in waypoints.enumerated() { let marker = GMSMarker() marker.position = waypoint marker.title = "Stop \(index + 1)" // Color code the markers switch index { case 0: marker.icon = GMSMarker.markerImage(with: .green) marker.snippet = "Start" case waypoints.count - 1: marker.icon = GMSMarker.markerImage(with: .red) marker.snippet = "Destination" default: marker.icon = GMSMarker.markerImage(with: .blue) marker.snippet = "Waypoint" } navigationViewController.addMarker(marker) } } // MARK: - Toggle Display Options @IBAction func toggleTraffic(_ sender: UIButton) { navigationViewController.showsTrafficLayer.toggle() sender.setTitle( navigationViewController.showsTrafficLayer ? "Hide Traffic" : "Show Traffic", for: .normal ) } @IBAction func toggleIncidents(_ sender: UIButton) { navigationViewController.showsIncidentsLayer.toggle() sender.setTitle( navigationViewController.showsIncidentsLayer ? "Hide Incidents" : "Show Incidents", for: .normal ) } @IBAction func toggleSpeedLimitAlert(_ sender: UIButton) { navigationViewController.displaySpeedLimitAlert.toggle() sender.setTitle( navigationViewController.displaySpeedLimitAlert ? "Disable Speed Alerts" : "Enable Speed Alerts", for: .normal ) } @IBAction func showFullRoute(_ sender: UIButton) { navigationViewController.showsRouteOverview = true } @IBAction func focusOnLocation(_ sender: UIButton) { navigationViewController.showsRouteOverview = false navigationViewController.cameraMode = .following } // MARK: - Navigation Delegate func navigationViewController( _ navigationViewController: GMSNavigationViewController, didUpdate navigationUpdates: GMSNavigationUpdates, for routeToken: String ) { // Could respond to navigation updates to adjust display } } ``` -------------------------------- ### Get Time to Next Step Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Fetch the estimated time in seconds until the next navigation step. ```swift let secondsUntilTurn = Int(updates.timeToNextStep) print("Next turn in \(secondsUntilTurn) seconds") ``` -------------------------------- ### GMSRouteStep Properties Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Access properties of a GMSRouteStep to get navigation instruction details. ```APIDOC ## GMSRouteStep Properties ### instructionText **Type:** String, read-only **Description:** The human-readable instruction for this step (e.g., "Turn left onto Main Street"). ### distanceMeters **Type:** CLLocationDistance, read-only **Description:** The distance to travel during this step in meters. ### maneuverType **Type:** GMSManeuverType, read-only **Description:** The type of turn or maneuver required at this step. ### roadName **Type:** String?, read-only **Description:** The name of the road or street for this step, or nil if not available. ### location **Type:** CLLocationCoordinate2D, read-only **Description:** The geographic coordinate where this step begins. ### polyline **Type:** GMSPolyline?, read-only **Description:** The geometric representation of this step as a polyline. ``` -------------------------------- ### Compute Routes and Start Guidance with GMSNavigator Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/README.md Use GMSNavigator to compute routes between specified points and initiate turn-by-turn guidance. Requires setting a delegate for navigation events. ```swift let navigator = GMSNavigator() narrator.delegate = self narrator.computeRoutes(origin: start, destination: end, waypoints: nil) { result, error in if let route = result?.routes.first { navigator.startGuidance(for: route) } } ``` -------------------------------- ### Compute Test Routes Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md Compute routes between two specified coordinates for testing purposes. This example shows how to set origin and destination for route computation. ```swift // San Francisco to Los Angeles let origin = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) let destination = CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437) navigator.computeRoutes( origin: origin, destination: destination, waypoints: nil ) { result, error in // Test with known routes } ``` -------------------------------- ### Ensuring Route Availability by Recomputing Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/errors.md Implement a function to check if a route is stale (e.g., token is empty) and recompute it if necessary. This ensures that navigation starts with a valid and available route. ```swift func ensureRouteAvailable(_ route: GMSRoute) -> GMSRoute? { // If route seems stale, recompute let isStale = route.routeToken.isEmpty if isStale { // Recompute route var newRoute: GMSRoute? navigator.computeRoutes( origin: route.legs.first?.startLocation ?? CLLocationCoordinate2D(), destination: route.legs.last?.endLocation ?? CLLocationCoordinate2D(), waypoints: nil ) { result, error in newRoute = result?.routes.first } return newRoute } return route } ``` -------------------------------- ### Get Next Navigation Step Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Access the next navigation step, including instruction text and distance. Returns nil if there are no more steps. ```swift if let nextStep = updates.nextStep { print("Next: \(nextStep.instructionText)") print("Distance: \(nextStep.distanceMeters)m") } ``` -------------------------------- ### Example Usage of GMSRouteTrafficData Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Analyze traffic data for a given route, including its condition and estimated delay, and calculate the impact of the delay. ```swift import GoogleNavigation func analyzeTraffic(route: GMSRoute) { guard let traffic = route.trafficData else { print("No traffic data available") return } print("Traffic Analysis:") print(" Condition: \(traffic.condition)") print(" Estimated Delay: \(traffic.estimatedDelay)s") let baseTime = route.duration - traffic.estimatedDelay let delayPercent = (traffic.estimatedDelay / route.duration) * 100 print(" Delay Impact: \(String(format: "%.1f", delayPercent))%") } ``` -------------------------------- ### Get Step Location Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Retrieves the geographic coordinate where a navigation step begins. This is useful for pinpointing the start of a maneuver. ```swift let stepLocation = step.location ``` -------------------------------- ### Update UI with Navigation State Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Example implementation of updating UI elements based on GMSNavigationUpdates. Demonstrates updating labels for distance, time, road name, speed, next instruction, and speed limit. ```swift import GoogleNavigation class NavigationViewController: UIViewController, GMSNavigatorDelegate { let navigator = GMSNavigator() override func viewDidLoad() { super.viewDidLoad() navigator.delegate = self } func navigator( _ navigator: GMSNavigator, didUpdate navigationState: GMSNavigationState ) { // Called when navigation state changes } func updateUI(with updates: GMSNavigationUpdates) { // Update distance label let distanceKm = updates.distanceToFinalDestination / 1000 distanceLabel.text = String(format: "%.1f km", distanceKm) // Update time label let timeMinutes = Int(updates.timeToFinalDestination) / 60 timeLabel.text = "\(timeMinutes) min" // Update current road if let road = updates.currentRoadName { roadLabel.text = road } // Update speed speedLabel.text = "\(updates.currentSpeed) km/h" // Update next instruction if let nextStep = updates.nextStep { instructionLabel.text = nextStep.instructionText let distanceToTurn = Int(updates.distanceToNextStep) distanceToTurnLabel.text = "\(distanceToTurn)m" } // Check speed limit if let speedLimit = updates.speedLimit { speedLimitLabel.text = "\(speedLimit) km/h" let currentSpeed = updates.currentSpeed if currentSpeed > speedLimit { speedLimitLabel.textColor = .red } else { speedLimitLabel.textColor = .green } } } } ``` -------------------------------- ### Requesting Location Permissions Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md This Swift code demonstrates how to request location permissions and start location updates using CoreLocation. Ensure background modes are enabled for turn-by-turn navigation. ```swift import CoreLocation class NavigationController: UIViewController { let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Request location permissions locationManager.requestWhenInUseAuthorization() // Or request background location (for turn-by-turn) locationManager.requestAlwaysAndWhenInUseAuthorization() // Start updating location locationManager.startUpdatingLocation() } } ``` -------------------------------- ### Handling Route Not Available Error Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/errors.md Catch the specific error code for a unavailable route when attempting to start guidance. This indicates the route may have expired or been purged from the cache. ```swift do { try navigator.startGuidance(for: route) } catch let error as NSError where error.code == 6002 { print("Route is no longer available") // Recompute a new route } ``` -------------------------------- ### Handle Location Permission Changes Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/errors.md Implement the delegate method to respond to changes in the user's location permission status. This allows your app to take appropriate action, such as starting navigation or prompting the user to enable settings. ```swift func locationManager( _ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus ) { switch status { case .authorizedWhenInUse, .authorizedAlways: // Start navigation case .denied, .restricted: // Show settings prompt case .notDetermined: // Permission not yet requested @unknown default: break } } ``` -------------------------------- ### GMSNavigator.startGuidance() Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/INDEX.md Initiates turn-by-turn navigation. Navigation updates are managed through navigation-state.md, and callbacks are handled via delegate methods in core-classes.md. ```APIDOC ## GMSNavigator.startGuidance() ### Description Starts turn-by-turn navigation guidance. ### Method Objective-C: `startGuidance` (refer to `GMSNavigator` class documentation for full signature) ### Endpoint N/A (SDK method) ### Parameters Refer to `GMSNavigator` class documentation for detailed parameter information. ### Request Example N/A (SDK method) ### Response N/A (SDK method) ### Response Example N/A (SDK method) ``` -------------------------------- ### Configure API Key and Initialize Navigation SDK Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md This snippet shows how to configure the API key (preferably via Info.plist) and initialize the GMSNavigationViewController. It also demonstrates setting up location services and display options for traffic, incidents, and speed limits. ```swift import UIKit import GoogleNavigation import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Configure API key via Info.plist (preferred) // Or programmatically: // GMSServices.setAPIKey("YOUR_API_KEY") return true } } class NavigationViewController: UIViewController, GMSNavigationViewControllerDelegate { var navigationViewController: GMSNavigationViewController? let navigator = GMSNavigator() let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad( locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() // Initialize navigation view controller navigationViewController = GMSNavigationViewController() navigationViewController?.delegate = self // Configure display options navigationViewController?.showsTrafficLayer = true navigationViewController?.showsIncidentsLayer = true navigationViewController?.displaySpeedLimitAlert = true // Set navigator delegate navigator.delegate = self // Add navigation view to hierarchy addChild(navigationViewController!) view.addSubview(navigationViewController!.view) navigationViewController!.view.frame = view.bounds navigationViewController!.didMove(toParent: self) } func startNavigation() { let origin = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) let destination = CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437) navigator.computeRoutes( origin: origin, destination: destination, waypoints: nil ) { [weak self] result, error in guard let self = self, let result = result else { return } if let route = result.routes.first { self.navigator.startGuidance(for: route) } } } } ``` -------------------------------- ### GMSNavigationViewController.cameraMode Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/MANIFEST.txt Gets or sets the camera mode for navigation. ```APIDOC ## GMSNavigationViewController.cameraMode (property) ### Description Gets or sets the camera mode for navigation. ### Method @property (nonatomic, assign) GMSCameraMode cameraMode; ### Parameters None ### Request Example None ### Response #### Success Response (200) - **cameraMode** (GMSCameraMode) - The current camera mode. #### Response Example None ``` -------------------------------- ### GMSNavigator Initialization Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Creates a new navigator instance. This is the entry point for using navigation features. ```APIDOC ## GMSNavigator The primary interface for programmatic navigation control and route management. ### Class Methods **class method: init()** Creates a new navigator instance. ```swift let navigator = GMSNavigator() ``` ``` -------------------------------- ### Get Route Distance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Access the total distance of the route in meters. ```swift let distance = route.distanceMeters print("Route distance: \(distance) meters") ``` -------------------------------- ### Get Route Coordinate Bounds Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Obtain the coordinate bounds of the entire route. ```swift let bounds = route.bounds() print("Northeast: \(bounds.northEast)") print("Southwest: \(bounds.southWest)") ``` -------------------------------- ### Get Route Token Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Retrieve the token that identifies the current route being navigated. ```swift let token = updates.routeToken ``` -------------------------------- ### Set Overview Camera Mode Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/location-and-camera.md Enable the 'Overview' camera mode to display the entire route. Set 'showsRouteOverview' to true to visualize the route bounds. ```swift navigationViewController.cameraMode = .overview // Show route bounds navigationViewController.showsRouteOverview = true ``` -------------------------------- ### Access Leg End Location Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Get the geographic coordinate where a route leg ends. ```swift let end = leg.endLocation ``` -------------------------------- ### Access Route Polyline Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Get the geometric representation of the route as a polyline and access its bounds. ```swift if let polyline = route.polyline { let bounds = polyline.bounds print("Route bounds: \(bounds)") } ``` -------------------------------- ### navigationViewControllerDidLoadNavigation(_:for:) Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Called after the navigation view is fully loaded and initialized. ```APIDOC ## navigationViewControllerDidLoadNavigation(_:for:) ### Description Called after the navigation view is fully loaded and initialized. ### Parameters #### Path Parameters - **navigationViewController** (GMSNavigationViewController) - Required - - **for** (String) - Required - ``` -------------------------------- ### Get Current Location Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Retrieve the current geographic coordinates (latitude and longitude) of the device. ```swift let location = updates.currentLocation print("Current: \(location.latitude), \(location.longitude)") ``` -------------------------------- ### Creating GMSRouteWaypoints Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Demonstrates how to initialize GMSRouteWaypoint objects with coordinates and optional titles for use in routing. ```swift import GoogleNavigation import CoreLocation func createWaypoints() -> [GMSRouteWaypoint] { let startWaypoint = GMSRouteWaypoint( coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), title: "San Francisco" ) let midWaypoint = GMSRouteWaypoint( coordinate: CLLocationCoordinate2D(latitude: 36.7783, longitude: -119.4179), title: "Fresno" ) let endWaypoint = GMSRouteWaypoint( coordinate: CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437), title: "Los Angeles" ) return [startWaypoint, midWaypoint, endWaypoint] } ``` -------------------------------- ### GMSRouteWaypoint Properties Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Access properties of a GMSRouteWaypoint to get its geographic coordinate, title, and place information. ```APIDOC ## GMSRouteWaypoint Properties ### Description Access properties of a GMSRouteWaypoint to get its geographic coordinate, title, and place information. ### Properties - **coordinate** (CLLocationCoordinate2D, read-only) The geographic coordinate of this waypoint. - **title** (String?, read-only) An optional name or title for this waypoint. - **place** (String?, read-only) An optional place identifier or address for this waypoint. ``` -------------------------------- ### System Frameworks Linking Settings Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/PACKAGE-MANIFEST.md Lists the system frameworks that the GoogleNavigationTarget links during compilation. These frameworks are essential for the application to run. ```swift linkerSettings: [ .linkedLibrary("xml2"), .linkedFramework("AudioToolbox"), .linkedFramework("AVFoundation"), .linkedFramework("CarPlay"), .linkedFramework("MapKit"), .linkedFramework("Metal"), .linkedFramework("WebKit"), .linkedFramework("UserNotifications"), ] ``` -------------------------------- ### Configure Route Display Options Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md Control route overview display, camera behavior, and the visibility of the recenter button. Animation for camera transitions can also be enabled. ```swift navigationViewController.showsRouteOverview = true navigationViewController.cameraMode = .following navigationViewController.recenterButtonVisible = true ``` -------------------------------- ### Getting Navigation Progress Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/INDEX.md Retrieves the current navigation state, remaining distance, and estimated time. ```APIDOC ## Navigation Progress ### Description Provides access to real-time navigation status and progress information. ### Properties/Methods - **navigator.navigationState**: Gets the current navigation state. - **navigator.remainingDistance()**: Returns the remaining distance in meters. - **navigator.remainingTime()**: Returns the estimated remaining time in seconds. ``` -------------------------------- ### Package Declaration for GoogleNavigation Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/PACKAGE-MANIFEST.md Defines the package name, supported platforms, products, and dependencies for the GoogleNavigation SDK. Ensure Swift 5.7 or later is used. ```swift let package = Package( name: "GoogleNavigation", platforms: [.iOS(.v16)], products: [ .library( name: "GoogleNavigation", targets: ["GoogleNavigationTarget", "GoogleNavigationSwiftTarget"]) ], dependencies: [ .package(url: "https://github.com/googlemaps/ios-maps-sdk", from: "10.15.0") ], targets: [ // See target definitions below ] ) ``` -------------------------------- ### Get Route Duration Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Retrieve the estimated travel time for the route in seconds and convert it to minutes. ```swift let duration = route.duration let minutes = Int(duration) / 60 print("Estimated duration: \(minutes) minutes") ``` -------------------------------- ### Get Bearing Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Obtain the device's current bearing (heading) in degrees, where 0° is north. ```swift let heading = updates.bearing print("Bearing: \(heading)°") ``` -------------------------------- ### GMSNavigationViewController Methods Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Control navigation guidance, camera, and map markers. ```APIDOC ## GMSNavigationViewController Methods ### Description Methods for controlling the navigation experience and map elements. ### Methods - **startGuidance(for:routeToken:)** Initiates turn-by-turn guidance for a specific route. #### Parameters - **for** (GMSRouteLeg) - Required - The route leg to navigate. - **routeToken** (String) - Required - Token identifying the route session. #### Throws May throw navigation-related errors if the route is invalid or unavailable. - **updateCamera(with:animated:)** Updates the navigation map camera to a specific position. #### Parameters - **with** (GMSCameraPosition) - Required - The new camera position. - **animated** (Bool) - Optional (Default: true) - Whether to animate the camera change. - **addMarker(_:)** Adds a marker to the navigation map. #### Parameters - **marker** (GMSMarker) - Required - The marker to add. - **removeMarker(_:)** Removes a marker from the navigation map. #### Parameters - **marker** (GMSMarker) - Required - The marker to remove. ``` -------------------------------- ### Simulate Location in Simulator Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md Instructions on how to simulate a location for testing purposes within the iOS Simulator using Xcode's scheme settings. ```swift // Simulate a location (uses Xcode scheme) // In Xcode: Scheme → Run → Diagnostics → Core Location ``` -------------------------------- ### Get Distance to Next Step Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Retrieve the remaining distance in meters until the next navigation step. ```swift print("Distance to next turn: \(updates.distanceToNextStep)m") ``` -------------------------------- ### Get Current Speed Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Obtain the device's current speed in kilometers per hour. ```swift print("Current speed: \(updates.currentSpeed) km/h") ``` -------------------------------- ### Get Leg Polyline Points Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Retrieve an array of coordinate points that define the geometry of a route leg. ```swift let points = leg.polylinePoints() print("Number of points: \(points.count)") ``` -------------------------------- ### Route Display Options Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/map-display.md Configure how the route is initially displayed on the map. ```APIDOC ## Route Display ### showsRouteOverview Controls whether the full route overview is displayed initially. - **Type:** Bool (read-write) - **Default:** `true` When `true`, the map initially shows the entire route. When `false`, the map focuses on the current location. ``` -------------------------------- ### Get Route Polyline Points Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Retrieve an array of coordinate points that define the route's geometry. ```swift let points = route.polylinePoints() for point in points { print("Point: \(point.latitude), \(point.longitude)") } ``` -------------------------------- ### GMSNavigationViewController Designated Initializers Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Supports standard UIKit initializers for programmatic or Interface Builder instantiation. ```APIDOC ## GMSNavigationViewController Designated Initializers ### Description Supports initialization via NSCoder for archived objects or Interface Builder. ### Method `init?(coder: NSCoder)` `init(nibName: String?, bundle: Bundle?)` ### Parameters #### Path Parameters - **coder** (NSCoder) - Required - The coder object for deserialization. - **nibName** (String?) - Optional - The name of the nib file to load. - **bundle** (Bundle?) - Optional - The bundle containing the nib file. ``` -------------------------------- ### Get Remaining Route Legs Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Access the array of remaining route legs from the current position to the destination. ```swift print("Legs remaining: \(updates.remainingRouteLegs.count)") ``` -------------------------------- ### Programmatically Configure API Key Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md Set the API key programmatically at application startup using GMSServices.setAPIKey. This must be done before using any Navigation SDK features. ```swift import GoogleNavigation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Set API key programmatically // Note: This must be done before using any Navigation SDK features GMSServices.setAPIKey("YOUR_API_KEY_HERE") return true } } ``` -------------------------------- ### Initialize GMSNavigationViewController Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/README.md Instantiate the primary view controller for navigation UI. Set its delegate to receive navigation events. ```swift let navigationViewController = GMSNavigationViewController() navigationViewController.delegate = self view.addSubview(navigationViewController.view) ``` -------------------------------- ### Get Remaining Distance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Returns the remaining distance to the destination in meters as an Int64. Useful for displaying progress to the user. ```swift let remainingDistance = navigator.remainingDistance() print("Distance remaining: \(remainingDistance)m") ``` -------------------------------- ### Check Network Reachability Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/errors.md This code snippet shows how to use the Network framework to monitor network status and determine if a connection is available before proceeding with network requests. ```swift import Network let monitor = NWPathMonitor() monitor.pathUpdateHandler = { path in if path.status == .connected { // Network available, safe to proceed } else { // Network unavailable, show offline message } } ``` -------------------------------- ### Get Navigation Progress Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/INDEX.md Retrieve the current navigation state, remaining distance in meters, and remaining time in seconds. ```swift navigator.navigationState // Current state ``` ```swift navigator.remainingDistance() // Distance in meters ``` ```swift navigator.remainingTime() // Time in seconds ``` -------------------------------- ### Configure Navigation Display Options Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/configuration.md Set traffic layer, incidents layer, and speed limit alerts visibility. Defaults are true for most options. ```swift let navigationViewController = GMSNavigationViewController() // Traffic layer visibility (default: true) navigationViewController.showsTrafficLayer = true // Incidents layer visibility (default: true) navigationViewController.showsIncidentsLayer = true // Speed limit alerts (default: true) navigationViewController.displaySpeedLimitAlert = true ``` -------------------------------- ### Get Distance to Next Waypoint Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Access the remaining distance in meters to the next waypoint. Requires an instance of GMSNavigationUpdates. ```swift if let updates = navigationUpdates { print("Distance to next waypoint: \(updates.distanceToNextWaypoint)m") } ``` -------------------------------- ### Access Route Waypoints Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Iterate through the waypoints that define the route, including start, intermediate, and end points, and print their coordinates. ```swift for (index, waypoint) in route.waypoints.enumerated() { print("Waypoint \(index): \(waypoint.coordinate)") } ``` -------------------------------- ### Instant Camera Transition Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/location-and-camera.md Update the camera position immediately without any animation. This is useful for instant changes in perspective. ```swift navigationViewController?.updateCamera(with: newPosition, animated: false) // Camera position updates immediately ``` -------------------------------- ### Navigation State Utility Functions Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Provides utility functions for checking navigation status and controlling guidance. Ensure the navigator object is properly initialized before use. ```swift func isNavigatingToDestination() -> Bool { return navigator.navigationState == .enroute } func stopNavigation() { if navigator.navigationState != .stopped { navigator.stopGuidance() } } ``` -------------------------------- ### Switch Camera Modes and Update Camera Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/location-and-camera.md Programmatically switch between 'Overview' and 'Following' camera modes, or update the camera to a custom position with animation. ```swift import GoogleNavigation class NavigationViewController: UIViewController { var navigationViewController: GMSNavigationViewController? @IBAction func switchToOverview(_ sender: UIButton) { navigationViewController?.cameraMode = .overview } @IBAction func switchToFollowing(_ sender: UIButton) { navigationViewController?.cameraMode = .following } @IBAction func customCameraPosition(_ sender: UIButton) { let position = GMSCameraPosition( target: CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437), zoom: 14.0, bearing: 45.0, viewingAngle: 30.0 ) navigationViewController?.updateCamera(with: position, animated: true) } } ``` -------------------------------- ### Get Remaining Time Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Returns the estimated remaining time to reach the destination in seconds as an Int64. Useful for ETA calculations. ```swift let remainingTime = navigator.remainingTime() print("Time remaining: \(remainingTime)s") ``` -------------------------------- ### Get Step Distance Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/routes-and-waypoints.md Retrieves the distance in meters to travel for a specific navigation step. Useful for displaying remaining distance. ```swift let distance = step.distanceMeters print("Travel \(distance)m for this step") ``` -------------------------------- ### Configure API Key Programmatically Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/README.md Alternatively, set the API key programmatically using GMSServices. This is useful for dynamic key management. ```swift GMSServices.setAPIKey("YOUR_API_KEY") ``` -------------------------------- ### Get Current Road Name Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Access the name of the road currently being traveled on. Returns nil if the road name is not available. ```swift if let roadName = updates.currentRoadName { print("Road: \(roadName)") } ``` -------------------------------- ### Set Following Camera Mode Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/location-and-camera.md Enable the 'Following' camera mode, where the camera tracks the vehicle's location and heading. Ensure the recenter button is visible for manual adjustments. ```swift navigationViewController.cameraMode = .following // Recenter button visible for manual recenter navigationViewController.recenterButtonVisible = true ``` -------------------------------- ### Get Distance to Final Destination Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/navigation-state.md Obtain the remaining distance in meters to the final destination. Converts the distance to kilometers for display. ```swift let remainingKm = updates.distanceToFinalDestination / 1000 print("Distance to destination: \(remainingKm) km") ``` -------------------------------- ### Show or Hide Route Overview Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/map-display.md Control whether the entire route is displayed initially on the map. When false, the map focuses on the current location. ```swift navigationViewController.showsRouteOverview = true // Show overview navigationViewController.showsRouteOverview = false // Show current location ``` -------------------------------- ### GMSNavigator.computeRoutes Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/MANIFEST.txt Computes routes between an origin and destination, with optional waypoints. The result is returned via a callback. ```APIDOC ## GMSNavigator.computeRoutes(origin:destination:waypoints:callback:) ### Description Computes routes between an origin and destination, with optional waypoints. The result is returned via a callback. ### Method - (void)computeRoutesWithOrigin:(CLLocationCoordinate2D)origin destination:(CLLocationCoordinate2D)destination waypoints:(nullable NSArray *)waypoints callback:(nullable GMSNavigationRouteCallback)callback; ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **callback** (GMSNavigationRouteCallback) - A callback function that receives the computed routes or an error. #### Response Example None ``` -------------------------------- ### Get Active Route Token Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/core-classes.md Retrieves the unique token for the currently active route. Returns nil if no route is currently active. ```swift if let token = navigator.currentRouteToken { print("Active route token: \(token)") } ``` -------------------------------- ### Camera Modes Source: https://github.com/googlemaps/ios-navigation-sdk/blob/main/_autodocs/api-reference/location-and-camera.md The Navigation SDK supports different camera behaviors during navigation, including Following and Overview modes. ```APIDOC ### Camera Modes The Navigation SDK supports different camera behaviors during navigation: **Following Mode** (Default) - Camera follows the vehicle's current location - Bearing is locked to vehicle heading - Automatically re-centers on vehicle ```swift navigationViewController.cameraMode = .following // Recenter button visible for manual recenter navigationViewController.recenterButtonVisible = true ``` **Overview Mode** - Shows full route from origin to destination - Fixed camera position - No automatic re-centering ```swift navigationViewController.cameraMode = .overview // Show route bounds navigationViewController.showsRouteOverview = true ``` **Example: Switch Camera Modes** ```swift import GoogleNavigation class NavigationViewController: UIViewController { var navigationViewController: GMSNavigationViewController? @IBAction func switchToOverview(_ sender: UIButton) { navigationViewController?.cameraMode = .overview } @IBAction func switchToFollowing(_ sender: UIButton) { navigationViewController?.cameraMode = .following } @IBAction func customCameraPosition(_ sender: UIButton) { let position = GMSCameraPosition( target: CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437), zoom: 14.0, bearing: 45.0, viewingAngle: 30.0 ) navigationViewController?.updateCamera(with: position, animated: true) } } ``` ```