### Install iOS Dependencies Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/example/README.md Navigate to the example/ios folder and run 'pod install' to install necessary dependencies for the iOS sample application. ```bash pod install ``` -------------------------------- ### Install Workspace Dependencies Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/example/README.md Run 'yarn install' in the example folder to install all necessary workspace dependencies before running the application. ```bash yarn install ``` -------------------------------- ### Run CarPlay Example Project Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CARPLAY.md Execute the command to start the CarPlay example application. This command builds and launches the iOS application with CarPlay support. ```bash yarn example ios:carplay ``` -------------------------------- ### Start Navigation with Destination and Routing Options Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Sets a destination with specified routing and display options, then starts navigation guidance. Ensure the SDK has acquired user location before calling. ```tsx try { const waypoint = { title: 'Destination', position: { lat: 37.4220679, lng: -122.0859545, }, }; const routingOptions = { travelMode: TravelMode.DRIVING, avoidFerries: false, avoidTolls: false, }; const displayOptions: DisplayOptions = { showDestinationMarkers: true, showStopSigns: true, showTrafficLights: true, }; await navigationController.setDestinations([waypoint], { routingOptions, displayOptions }); await navigationController.startGuidance(); } catch (error) { console.error('Error starting navigation', error); } ``` -------------------------------- ### Install React Native Navigation SDK Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Install the package using npm. Ensure you are using a compatible React Native version (0.79+ with new architecture enabled). ```shell npm i @googlemaps/react-native-navigation-sdk ``` -------------------------------- ### Format Objective-C Code Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Run this script to format all Objective-C files in the /ios and /example/ios directories according to Google's style guide. ```bash ./scripts/format-objc.sh ``` -------------------------------- ### NavigationView Component Example Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt This example demonstrates how to use the NavigationView component to display a map with navigation UI. It includes configuration for map settings, navigation UI preferences, platform-specific styling, and event callbacks. Ensure all necessary imports are included. ```tsx import React, { useState, useCallback } from 'react'; import { StyleSheet, View } from 'react-native'; import { NavigationView, MapColorScheme, NavigationNightMode, NavigationUIEnabledPreference, CameraPerspective, type MapViewController, type NavigationViewController, type LatLng, type Marker, } from '@googlemaps/react-native-navigation-sdk'; function NavigationMapScreen() { const [mapViewController, setMapViewController] = useState(null); const [navViewController, setNavViewController] = useState(null); const onMapReady = useCallback(() => { console.log('Map is ready'); }, []); const onMapClick = useCallback((latLng: LatLng) => { console.log(`Clicked: ${latLng.lat}, ${latLng.lng}`); }, []); const onMarkerClick = useCallback((marker: Marker) => { console.log(`Marker clicked: ${marker.title}`); mapViewController?.removeMarker(marker.id); }, [mapViewController]); const onRecenterButtonClick = useCallback(() => { navViewController?.setFollowingPerspective(CameraPerspective.TILTED, { zoomLevel: 17, }); }, [navViewController]); return ( console.log('Polyline:', polyline.id)} onPolygonClick={(polygon) => console.log('Polygon:', polygon.id)} onCircleClick={(circle) => console.log('Circle:', circle.id)} onGroundOverlayClick={(overlay) => console.log('Overlay:', overlay.id)} onMarkerInfoWindowTapped={(marker) => console.log('Info window:', marker.title)} onRecenterButtonClick={onRecenterButtonClick} onPromptVisibilityChanged={(visible) => console.log('Prompt visible:', visible)} // Controller callbacks onMapViewControllerCreated={setMapViewController} onNavigationViewControllerCreated={setNavViewController} /> ); } const styles = StyleSheet.create({ container: { flex: 1 }, map: { flex: 1 }, }); ``` -------------------------------- ### Format Java Code Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Run this script to format all Java files in the /android and /example/android directories according to Google's style guide. ```bash ./scripts/format-java.sh ``` -------------------------------- ### Run React Native App on iOS Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/example/README.md Execute 'npx react-native run-ios' in the example folder to build and run the iOS version of the sample application. ```bash npx react-native run-ios ``` -------------------------------- ### Migrate Navigation Event Listeners (0.13.x to 0.14.x) Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md Compares the event listener setup before and after version 0.14.x. Version 0.14.x simplifies listener setup by using individual `setOn*` props and a single `removeAllListeners` cleanup function. ```tsx import React, { useEffect, useMemo, useState, useCallback } from 'react'; import { NavigationView, useNavigation, type MapViewCallbacks, type NavigationCallbacks, type NavigationViewCallbacks, } from '@googlemaps/react-native-navigation-sdk'; const NavigationScreen = () => { const [mapViewController, setMapViewController] = useState(null); const [navViewController, setNavViewController] = useState(null); const { navigationController, addListeners, removeListeners } = useNavigation(); const navigationCallbacks: NavigationCallbacks = useMemo(() => ({ onArrival: (event) => console.log('Arrived', event), onRouteChanged: () => console.log('Route changed'), }), []); const mapViewCallbacks: MapViewCallbacks = useMemo(() => ({ onMapReady: () => console.log('Map ready'), onMapClick: (latLng) => console.log('Clicked', latLng), }), []); const navigationViewCallbacks: NavigationViewCallbacks = { onRecenterButtonClick: () => console.log('Recenter'), }; useEffect(() => { addListeners(navigationCallbacks); return () => removeListeners(navigationCallbacks); }, [navigationCallbacks, addListeners, removeListeners]); useEffect(() => { navViewController?.setSpeedometerEnabled(true); mapViewController?.setMyLocationEnabled(true); }, [navViewController, mapViewController]); return ( ); }; ``` ```tsx import React, { useEffect, useState, useCallback } from 'react'; import { NavigationView, useNavigation, } from '@googlemaps/react-native-navigation-sdk'; const NavigationScreen = () => { const [mapViewController, setMapViewController] = useState(null); const [navViewController, setNavViewController] = useState(null); const { navigationController, removeAllListeners, setOnArrival, setOnRouteChanged, } = useNavigation(); // Set up navigation listeners useEffect(() => { setOnArrival((event) => console.log('Arrived', event)); setOnRouteChanged(() => console.log('Route changed')); return () => removeAllListeners(); }, [setOnArrival, setOnRouteChanged, removeAllListeners]); // Callbacks are now regular functions passed directly as props const onMapReady = useCallback(() => console.log('Map ready'), []); const onMapClick = useCallback((latLng) => console.log('Clicked', latLng), []); const onRecenterButtonClick = useCallback(() => console.log('Recenter'), []); return ( ); }; ``` -------------------------------- ### Reinstall Pods after iOS Configuration Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md After updating the `ios/Podfile` to enable the New Architecture, run `pod install` in the `ios` directory. ```bash cd ios && pod install ``` -------------------------------- ### Run React Native App on Android Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/example/README.md Execute 'npx react-native run-android' in the example folder to build and run the Android version of the sample application. ```bash npx react-native run-android ``` -------------------------------- ### Build Android Integration Tests with Detox Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Use this command to build the integration tests for the Android platform. Ensure Detox is installed and configured. ```bash yarn run example detox:build:android-release ``` -------------------------------- ### Start Navigation with Route Token Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Starts navigation using a pre-computed route token from the Routes API. Waypoints must match those used for token generation. Routing options and route token options are mutually exclusive. ```tsx const waypoint = { title: 'Destination', position: { lat: 37.7749, lng: -122.4194 }, }; const routeTokenOptions = { routeToken: 'your-route-token-from-routes-api', travelMode: TravelMode.DRIVING, // Must match the travel mode used to generate the token }; await navigationController.setDestinations([waypoint], { routeTokenOptions }); await navigationController.startGuidance(); ``` -------------------------------- ### NavigationController Methods Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt Methods for controlling the navigation session, such as initializing, setting destinations, starting guidance, configuring audio, and retrieving route information. ```APIDOC ## NavigationController Methods ### Description Provides methods to control the navigation session including route management, guidance control, and location services. ### Methods #### `areTermsAccepted()` - **Description**: Checks if the terms and conditions have been accepted. - **Method**: `async` - **Returns**: `Promise` - `true` if terms are accepted, `false` otherwise. #### `showTermsAndConditionsDialog(options)` - **Description**: Displays the Terms and Conditions dialog to the user. - **Method**: `async` - **Parameters**: - `options` (object) - Optional configuration for the dialog. - `uiParams` (object) - UI customization parameters. - `backgroundColor` (string) - Background color of the dialog. - **Returns**: `Promise` - `true` if terms were accepted, `false` otherwise. #### `init()` - **Description**: Initializes the navigation session. - **Method**: `async` - **Returns**: `Promise` - Status of the initialization. #### `getNavSDKVersion()` - **Description**: Retrieves the version of the Navigation SDK. - **Method**: `async` - **Returns**: `Promise` - The SDK version. #### `setDestinations(waypoints, options)` - **Description**: Sets multiple destinations (waypoints) for navigation. - **Method**: `async` - **Parameters**: - `waypoints` (array) - An array of waypoint objects. Each object can have `position` ({lat, lng}) or `placeId`. - `options` (object) - Optional routing configurations. - `routingOptions` (object) - Options for routing. - `travelMode` (number) - Travel mode (e.g., 0 for DRIVING). - `routingStrategy` (number) - Routing strategy (e.g., 0 for DEFAULT_BEST). - `alternateRoutesStrategy` (number) - Strategy for alternate routes (e.g., 0 for SHOW_ALL). - **Returns**: `Promise` - Status of setting the destinations. #### `startGuidance()` - **Description**: Starts the navigation guidance. - **Method**: `async` #### `setAudioGuidanceType(type)` - **Description**: Sets the type of audio guidance. - **Method**: `void` - **Parameters**: - `type` (AudioGuidance) - The type of audio guidance (e.g., `AudioGuidance.VOICE_ALERTS_AND_GUIDANCE`). #### `setSpeedAlertOptions(options)` - **Description**: Configures options for speed alerts. - **Method**: `async` - **Parameters**: - `options` (object) - Speed alert configuration. - `minorSpeedAlertPercentThreshold` (number) - Percentage threshold for minor speed alerts. - `majorSpeedAlertPercentThreshold` (number) - Percentage threshold for major speed alerts. - `severityUpgradeDurationSeconds` (number) - Duration in seconds for severity upgrade. #### `setTurnByTurnLoggingEnabled(enabled)` - **Description**: Enables or disables turn-by-turn logging. - **Method**: `void` - **Parameters**: - `enabled` (boolean) - `true` to enable, `false` to disable. #### `setBackgroundLocationUpdatesEnabled(enabled)` - **Description**: Enables or disables background location updates (iOS only). - **Method**: `void` - **Parameters**: - `enabled` (boolean) - `true` to enable, `false` to disable. #### `getCurrentRouteSegment()` - **Description**: Retrieves the current route segment. - **Method**: `async` - **Returns**: `Promise` - An object representing the current route segment, including `destinationWaypoint`. #### `getRouteSegments()` - **Description**: Retrieves all route segments. - **Method**: `async` - **Returns**: `Promise` - An array of route segment objects. #### `getCurrentTimeAndDistance()` - **Description**: Gets the estimated remaining time and distance to the destination. - **Method**: `async` - **Returns**: `Promise` - An object containing `meters` and `seconds`. #### `getTraveledPath()` - **Description**: Retrieves the path traveled so far. - **Method**: `async` - **Returns**: `Promise` - An array of points representing the traveled path. #### `stopGuidance()` - **Description**: Stops the navigation guidance. - **Method**: `async` #### `clearDestinations()` - **Description**: Clears all set destinations. - **Method**: `async` #### `cleanup()` - **Description**: Cleans up the navigation session resources. - **Method**: `async` ``` -------------------------------- ### Build iOS Integration Tests with Detox Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Use this command to build the integration tests for the iOS platform. Ensure Detox is installed and configured. ```bash yarn run example detox:build:ios-release ``` -------------------------------- ### Customize Android Auto Template Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/ANDROIDAUTO.md Override `onGetTemplate` to customize the Android Auto experience by building a `NavigationTemplate`. This example shows how to add actions to an `ActionStrip` and a map-specific `ActionStrip`. ```java @NonNull @Override public Template onGetTemplate() { /** ... */ @SuppressLint("MissingPermission") NavigationTemplate.Builder navigationTemplateBuilder = new NavigationTemplate.Builder() .setActionStrip( new ActionStrip.Builder() .addAction( new Action.Builder() .setTitle("Re-center") .setOnClickListener( () -> { if (mGoogleMap == null) return; mGoogleMap.followMyLocation(GoogleMap.CameraPerspective.TILTED); } ) .build()) .addAction( new Action.Builder() .setTitle("Custom event") .setOnClickListener( () -> { WritableMap map = Arguments.createMap(); map.putString("sampleKey", "sampleValue"); sendCustomEvent("sampleEvent", map); } ) .build()) .build()) .setMapActionStrip(new ActionStrip.Builder().addAction(Action.PAN).build()); /** ... */ } ``` -------------------------------- ### Navigate Using Route Token Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt Use a pre-computed route token from the Google Maps Routes API to set destinations and start navigation. Ensure the travel mode in routeTokenOptions matches the mode used to generate the token. ```typescript import { useNavigation, RouteStatus, TravelMode, } from '@googlemaps/react-native-navigation-sdk'; function RouteTokenExample() { const { navigationController } = useNavigation(); const navigateWithRouteToken = async () => { // Route token obtained from Google Maps Routes API const routeToken = 'CpoBCi0KB...long_route_token_string'; const routeStatus = await navigationController.setDestinations( [ { position: { lat: 37.7749, lng: -122.4194 }, title: 'San Francisco' }, { position: { lat: 34.0522, lng: -118.2437 }, title: 'Los Angeles' }, ], { // Use routeTokenOptions instead of routingOptions // These are mutually exclusive routeTokenOptions: { routeToken: routeToken, travelMode: TravelMode.DRIVING, // Must match token's travel mode }, displayOptions: { showDestinationMarkers: true, }, } ); if (routeStatus === RouteStatus.OK) { await navigationController.startGuidance(); } }; return null; } ``` -------------------------------- ### Initialize Navigation with Status Return (v0.14.x) Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md v0.14.x introduces a new initialization flow. First, `showTermsAndConditionsDialog` is called, followed by `init`, which returns a `NavigationSessionStatus`. ```tsx // Component - Initialization with status return import { useNavigation, NavigationSessionStatus } from '@googlemaps/react-native-navigation-sdk'; const { navigationController, setOnNavigationReady } = useNavigation(); useEffect(() => { // onNavigationReady is still called on successful init setOnNavigationReady(() => console.log('Navigation ready')); }, []); const initNavigation = async () => { // Step 1: Show Terms and Conditions dialog const termsAccepted = await navigationController.showTermsAndConditionsDialog(); if (!termsAccepted) { console.log('User declined terms'); return; } // Step 2: Initialize navigation session const status = await navigationController.init(); switch (status) { case NavigationSessionStatus.OK: console.log('Navigation initialized successfully'); break; case NavigationSessionStatus.NOT_AUTHORIZED: console.error('API key not authorized'); break; case NavigationSessionStatus.TERMS_NOT_ACCEPTED: console.error('Terms not accepted'); break; case NavigationSessionStatus.LOCATION_PERMISSION_MISSING: console.error('Location permission required'); break; case NavigationSessionStatus.NETWORK_ERROR: console.error('Network error'); break; default: console.error('Unknown error:', status); } }; ``` -------------------------------- ### Initialize and Manage Navigation Session Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt Handles terms and conditions acceptance and initializes the navigation session. Logs the SDK version upon successful initialization. ```tsx import { useNavigation, RouteStatus, AudioGuidance, NavigationSessionStatus, } from '@googlemaps/react-native-navigation-sdk'; function NavigationExample() { const { navigationController } = useNavigation(); // Initialize and manage navigation session const manageSession = async () => { // Check if terms already accepted const termsAccepted = await navigationController.areTermsAccepted(); if (!termsAccepted) { // Show ToS dialog with custom options const accepted = await navigationController.showTermsAndConditionsDialog({ uiParams: { backgroundColor: '#F5F5F5' }, }); if (!accepted) return; } // Initialize navigation const status = await navigationController.init(); if (status !== NavigationSessionStatus.OK) { throw new Error(`Init failed: ${status}`); } // Get SDK version const version = await navigationController.getNavSDKVersion(); console.log('Nav SDK version:', version); }; return null; } ``` -------------------------------- ### Initializing Navigation Session Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md Steps to initialize the navigation session, including showing the Terms and Conditions dialog and handling the initialization status. ```APIDOC ## Initializing Navigation Session ### Description This section outlines the process of initializing the navigation session, which involves user consent for terms and conditions and then calling the initialization method. ### Method `async` function ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```tsx import { useNavigation, NavigationSessionStatus } from '@googlemaps/react-native-navigation-sdk'; const { navigationController, setOnNavigationReady } = useNavigation(); useEffect(() => { setOnNavigationReady(() => console.log('Navigation ready')); }, []); const initNavigation = async () => { // Step 1: Show Terms and Conditions dialog const termsAccepted = await navigationController.showTermsAndConditionsDialog(); if (!termsAccepted) { console.log('User declined terms'); return; } // Step 2: Initialize navigation session const status = await navigationController.init(); switch (status) { case NavigationSessionStatus.OK: console.log('Navigation initialized successfully'); break; case NavigationSessionStatus.NOT_AUTHORIZED: console.error('API key not authorized'); break; case NavigationSessionStatus.TERMS_NOT_ACCEPTED: console.error('Terms not accepted'); break; case NavigationSessionStatus.LOCATION_PERMISSION_MISSING: console.error('Location permission required'); break; case NavigationSessionStatus.NETWORK_ERROR: console.error('Network error'); break; default: console.error('Unknown error:', status); } }; ``` ### Response #### Success Response (200) - **status** (NavigationSessionStatus) - Indicates the result of the initialization. #### Response Example ```json { "status": "OK" } ``` ``` -------------------------------- ### Initialize Navigation with Try-Catch (v0.13.x) Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md In v0.13.x, navigation initialization used a try-catch block to handle errors, with success and error events managed via callbacks. ```tsx // Component - Initialization with try-catch import { useNavigation } from '@googlemaps/react-native-navigation-sdk'; const { navigationController, setOnNavigationReady, setOnNavigationInitError } = useNavigation(); useEffect(() => { setOnNavigationReady(() => console.log('Navigation ready')); setOnNavigationInitError((errorCode) => console.error('Init error:', errorCode)); }, []); const initNavigation = async () => { try { await navigationController.init({ termsAndConditionsDialogTitle: 'Terms', termsAndConditionsDialogCompanyName: 'My Company', showOnlyDisclaimer: false, }); // Success handled via onNavigationReady event } catch (error) { // Error handled via onNavigationInitError event console.error('Init failed', error); } }; ``` -------------------------------- ### Initialize NavigationProvider Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Wrap your application with the NavigationProvider component to provide navigation context. Configure terms and conditions dialog and task removal behavior. ```tsx import React from 'react'; import { NavigationProvider, TaskRemovedBehavior, } from '@googlemaps/react-native-navigation-sdk'; const App = () => { return ( {/* Add your application components here */} ); }; export default App; ``` -------------------------------- ### Set Multiple Destinations with Routing Options Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt Sets multiple destinations (waypoints) for a navigation route, including options for travel mode, routing strategy, and alternate routes. Starts guidance if the route is set successfully. ```tsx const waypoints = [ { position: { lat: -33.8688, lng: 151.2093 }, title: 'Sydney' }, { position: { lat: -33.9173, lng: 151.2313 }, title: 'Bondi Beach' }, { placeId: 'ChIJP5iLHkCuEmsRwMwyFmh9AQU', title: 'Sydney Airport' }, ]; const routeStatus = await navigationController.setDestinations(waypoints, { routingOptions: { travelMode: 0, // DRIVING routingStrategy: 0, // DEFAULT_BEST alternateRoutesStrategy: 0, // SHOW_ALL }, }); if (routeStatus === RouteStatus.OK) { await navigationController.startGuidance(); } ``` -------------------------------- ### Initialize NavigationProvider Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt The NavigationProvider must wrap any components that use navigation features. Configure terms and conditions dialog options and service behavior. ```tsx import React from 'react'; import { NavigationProvider, TaskRemovedBehavior, } from '@googlemaps/react-native-navigation-sdk'; export default function App() { return ( {/* Your app components */} ); } ``` -------------------------------- ### Run iOS Integration Tests with Detox Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Execute this command to run the integration tests for the iOS platform using Detox. This verifies the plugin's functionality against the native Navigation SDK. ```bash yarn run example detox:test:ios-release ``` -------------------------------- ### useNavigationAuto Return Values Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md The `useNavigationAuto` hook provides controllers and functions for managing automatic screen navigation and listeners. ```APIDOC ## useNavigationAuto Return Values ### Description The `useNavigationAuto` hook returns an object containing controllers and functions for managing automatic screen navigation features. ### Return Values #### `mapViewAutoController` - **Type**: `MapViewAutoController` - **Description**: Controller for auto screen map operations. #### `removeAllListeners` - **Type**: `() => void` - **Description**: Removes all registered auto listeners. #### `setOnAutoScreenAvailabilityChanged` - **Type**: `(listener: ((available: boolean) => void) | null | undefined) => void` - **Description**: Sets or clears a listener for auto screen availability changes. #### `setOnCustomNavigationAutoEvent` - **Type**: `(listener: ((event: CustomAutoEvent) => void) | null | undefined) => void` - **Description**: Sets or clears a listener for custom auto navigation events. ## MapViewAutoController Methods ### Description The `MapViewAutoController` extends `MapViewController` and provides additional methods for controlling map operations, particularly for auto screen features. ### Methods #### `cleanup()` - **Returns**: `void` - **Description**: Cleans up the auto screen resources. #### `isAutoScreenAvailable()` - **Returns**: `Promise` - **Description**: Checks if auto screen (Android Auto/CarPlay) is available. *Note: All methods from `MapViewController` are also available on `MapViewAutoController`.* ``` -------------------------------- ### Run Android Integration Tests with Detox Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Execute this command to run the integration tests for the Android platform using Detox. Ensure an emulator named "Android_Emulator" is created beforehand if one does not exist. ```bash yarn run example detox:test:android-release ``` -------------------------------- ### Enable New Architecture on iOS Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md Update the `RCT_NEW_ARCH_ENABLED` environment variable in `ios/Podfile` to `'1'` and then reinstall pods. ```diff ```diff - ENV['RCT_NEW_ARCH_ENABLED'] = '0' + ENV['RCT_NEW_ARCH_ENABLED'] = '1' ``` ``` -------------------------------- ### Configure iOS API Key Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/example/README.md Copy Keys.plist.sample to Keys.plist and add your Google API key. This key is required for the iOS application to function correctly. ```xml API_KEY Your API KEY ``` -------------------------------- ### Clone the Repository Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Clone the project repository to your local machine. Ensure you have configured your SSH key with GitHub. ```bash git clone git@github.com:/googlemaps/react-native-navigation-sdk.git ``` -------------------------------- ### NavigationController Methods Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md This section outlines the core methods of the NavigationController, detailing their purpose, parameters, and return values. ```APIDOC ## NavigationController Methods ### areTermsAccepted() #### Description Check if terms and conditions have been accepted. ### Method `Promise` ### areTermsAccepted() ### resetTermsAccepted() #### Description Reset the Terms and Conditions acceptance state. ### Method `Promise` ### resetTermsAccepted() ### init() #### Description Initialize the navigation session. ### Method `Promise` ### init() ### cleanup() #### Description Clean up the navigation controller. ### Method `Promise` ### cleanup() ### getNavSDKVersion() #### Description Get the Navigation SDK version. ### Method `Promise` ### getNavSDKVersion() ### setDestinations(destinations: Waypoint[], routingOptions?, displayOptions?) #### Description Set navigation destinations. ### Method `Promise` ### setDestinations(destinations: Waypoint[], routingOptions?, displayOptions?) ### setDestination(waypoint: Waypoint, routingOptions?, displayOptions?) #### Description Set a single navigation destination. ### Method `Promise` ### setDestination(waypoint: Waypoint, routingOptions?, displayOptions?) ### clearDestinations() #### Description Clear all destinations. ### Method `Promise` ### clearDestinations() ### continueToNextDestination() #### Description Navigate to the next destination in the list. ### Method `Promise` ### continueToNextDestination() ### startGuidance() #### Description Start turn-by-turn navigation guidance. ### Method `Promise` ### startGuidance() ### stopGuidance() #### Description Stop navigation guidance. ### Method `Promise` ### stopGuidance() ### getCurrentTimeAndDistance() #### Description Get time and distance to current destination. ### Method `Promise` ### getCurrentTimeAndDistance() ### getCurrentRouteSegment() #### Description Get the current route segment. ### Method `Promise` ### getCurrentRouteSegment() ### getRouteSegments() #### Description Get all route segments. ### Method `Promise` ### getRouteSegments() ### getTraveledPath() #### Description Get the path traveled so far. ### Method `Promise` ### getTraveledPath() ### setAudioGuidanceType(type: AudioGuidanceType) #### Description Set audio guidance type (SILENT, ALERTS_ONLY, VOICE_ALERTS_AND_GUIDANCE). ### Method `Promise` ### setAudioGuidanceType(type: AudioGuidanceType) ### setSpeedAlertOptions(options: SpeedAlertOptions) #### Description Configure speed alert thresholds. ### Method `Promise` ### setSpeedAlertOptions(options: SpeedAlertOptions) ### setAbnormalTerminatingReportingEnabled(enabled: boolean) #### Description Enable/disable abnormal termination reporting. ### Method `void` ### setAbnormalTerminatingReportingEnabled(enabled: boolean) ### startUpdatingLocation() #### Description Start receiving location updates. ### Method `Promise` ### startUpdatingLocation() ### stopUpdatingLocation() #### Description Stop receiving location updates. ### Method `void` ### stopUpdatingLocation() ``` -------------------------------- ### Configuration Props Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md These props allow you to configure the fundamental aspects of the navigation map, such as styling, initial state, and zoom levels. ```APIDOC ## Configuration Props ### Description Props to configure the map's appearance, initial state, and behavior. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Props - **style** (ViewStyle) - Optional - Style applied to the view container. Default: `{ flex: 1 }` - **mapId** (string) - Optional - Cloud-based map styling ID from Google Cloud Console. - **mapColorScheme** (MapColorScheme) - Optional - Color scheme for map tiles. Default: `FOLLOW_SYSTEM` (Options: `FOLLOW_SYSTEM`, `LIGHT`, `DARK`) - **mapStyle** (string) - Optional - Custom map styling via JSON. - **mapPadding** (Padding) - Optional - Padding applied to the map in pixels. - **initialCameraPosition** (CameraPosition) - Optional - Initial camera position when map loads. - **minZoomLevel** (number) - Optional - Minimum allowed zoom level. - **maxZoomLevel** (number) - Optional - Maximum allowed zoom level. - **navigationNightMode** (NavigationNightMode) - Optional - Night mode for navigation UI. Default: `AUTO` (Options: `AUTO`, `FORCE_DAY`, `FORCE_NIGHT`) - **navigationUIEnabledPreference** (NavigationUIEnabledPreference) - Optional - Initial navigation UI visibility. Default: `AUTOMATIC` (Options: `AUTOMATIC`, `DISABLED`) - **androidStylingOptions** (AndroidStylingOptions) - Optional - Android-specific navigation UI styling. - **iOSStylingOptions** (iOSStylingOptions) - Optional - iOS-specific navigation UI styling. ``` -------------------------------- ### Initialize Navigation Controller Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Initializes the navigation session after accepting terms and conditions. Handles various status codes for successful initialization or errors. ```tsx import { useNavigation, NavigationSessionStatus, } from '@googlemaps/react-native-navigation-sdk'; const { navigationController } = useNavigation(); const initializeNavigation = useCallback(async () => { // First show Terms and Conditions dialog (uses options from NavigationProvider) const termsAccepted = await navigationController.showTermsAndConditionsDialog(); if (!termsAccepted) { console.log('User declined terms'); return; } // Initialize the navigation session and check the status const status = await navigationController.init(); switch (status) { case NavigationSessionStatus.OK: console.log('Navigation initialized successfully'); break; case NavigationSessionStatus.NOT_AUTHORIZED: console.error('API key not authorized'); break; case NavigationSessionStatus.TERMS_NOT_ACCEPTED: console.error('Terms not accepted'); break; case NavigationSessionStatus.LOCATION_PERMISSION_MISSING: console.error('Location permission required'); break; case NavigationSessionStatus.NETWORK_ERROR: console.error('Network error'); break; default: console.error('Unknown error:', status); } }, [navigationController]); ``` -------------------------------- ### Add Navigation Event Listeners Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Sets up listeners for arrival, route changes, and navigation readiness. Includes logic for handling final destination arrival and cleaning up listeners on component unmount. ```tsx const { navigationController, removeAllListeners, setOnArrival, setOnRouteChanged, setOnNavigationReady, } = useNavigation(); useEffect(() => { setOnArrival((event: ArrivalEvent) => { if (event.isFinalDestination) { console.log('Final destination reached'); navigationController.stopGuidance(); } else { console.log('Continuing to the next destination'); navigationController.continueToNextDestination(); navigationController.startGuidance(); } }); setOnRouteChanged(() => console.log('Route changed')); setOnNavigationReady(() => console.log('Navigation ready')); // On cleanup, removeAllListeners() clears all at once. // Alternatively, clear individual listeners: setOnArrival(null) return () => removeAllListeners(); }, [ navigationController, setOnArrival, setOnRouteChanged, setOnNavigationReady, removeAllListeners, ]); ``` -------------------------------- ### Set Minimum SDK for Android Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Set the `minSdkVersion` to 24 or higher in your `android/app/build.gradle` file. This meets the minimum operating system requirement for the SDK on Android. ```groovy android { defaultConfig { minSdkVersion 24 } } ``` -------------------------------- ### Navigation Simulator Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt Methods for simulating navigation events and locations, useful for testing and development without physical movement. ```APIDOC ## Navigation Simulator ### Description Allows testing navigation without physical movement, useful for development and demos. ### Methods #### `simulateLocation(location)` - **Description**: Simulates the device being at a specific geographic location. - **Method**: `void` - **Parameters**: - `location` (object) - The location to simulate. - `lat` (number) - Latitude. - `lng` (number) - Longitude. #### `simulateLocationsAlongExistingRoute(options)` - **Description**: Simulates driving along the current route. - **Method**: `void` - **Parameters**: - `options` (object) - Simulation options. - `speedMultiplier` (number) - Multiplier for the simulation speed (e.g., 5 for 5x speed). #### `pauseLocationSimulation()` - **Description**: Pauses the current location simulation. - **Method**: `void` #### `resumeLocationSimulation()` - **Description**: Resumes a paused location simulation. - **Method**: `void` #### `stopLocationSimulation()` - **Description**: Stops the current location simulation. - **Method**: `void` ``` -------------------------------- ### Configure NavigationProvider (v0.13.x) Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md Before v0.14.x, the NavigationProvider accepted taskRemovedBehavior directly. ToS options were handled during initialization. ```tsx // App.tsx - Provider without ToS options {children} ``` -------------------------------- ### Simulator Methods Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md The Simulator object provides methods to test navigation without actual GPS. ```APIDOC ## Simulator Methods ### Description Methods for testing navigation by simulating GPS movement. ### Accessing the Simulator ```tsx const { navigationController } = useNavigation(); const simulator = navigationController.simulator; ``` ### Methods #### `simulateLocationsAlongExistingRoute(options: { speedMultiplier: number })` ##### Description Simulate driving along the current route at a given speed multiplier. ##### Method `void` ##### Parameters - **options** (object) - Required - Options for simulation. - **speedMultiplier** (number) - Required - Multiplier for the simulation speed. ##### Request Example ```json { "speedMultiplier": 5 } ``` #### `simulateLocation(location: LatLng)` ##### Description Set the user's location to a specific coordinate. ##### Method `void` ##### Parameters - **location** (LatLng) - Required - The target coordinates. - **lat** (number) - Required - Latitude. - **lng** (number) - Required - Longitude. ##### Request Example ```json { "lat": 37.7749, "lng": -122.4194 } ``` #### `pauseLocationSimulation()` ##### Description Pause the current location simulation. ##### Method `void` #### `resumeLocationSimulation()` ##### Description Resume a paused location simulation. ##### Method `void` #### `stopLocationSimulation()` ##### Description Stop the current location simulation. ##### Method `void` ``` -------------------------------- ### Show Terms and Conditions Dialog Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md Use the useNavigation hook to access the navigation controller and display the Terms and Conditions dialog. Options can be overridden during the call. ```tsx const { navigationController } = useNavigation(); const showTermsDialog = async () => { // Uses options from NavigationProvider by default const accepted = await navigationController.showTermsAndConditionsDialog(); return accepted; }; // You can also override specific options: const showTermsDialogWithOverride = async () => { const accepted = await navigationController.showTermsAndConditionsDialog({ showOnlyDisclaimer: true, // Override specific options }); return accepted; }; ``` -------------------------------- ### Create Pull Request Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Create a pull request on GitHub to submit your changes for review. This can be done via the GitHub website or using the Hub CLI. ```bash git pull-request ``` -------------------------------- ### useNavigation Hook Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/README.md The useNavigation hook provides access to the NavigationController and functions to set up listeners for navigation events. ```APIDOC ## NavigationController (useNavigation hook) ### Description The `useNavigation()` hook provides access to the `NavigationController` and listener setters for navigation events. ```tsx import { useNavigation } from '@googlemaps/react-native-navigation-sdk'; const { navigationController, removeAllListeners, setOnArrival, setOnRouteChanged, // ... other listener setters } = useNavigation(); ``` ### useNavigation Return Values | Property | Type | Description | | ---------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `navigationController` | `NavigationController` | Controller for navigation operations | | `removeAllListeners` | `() => void` | Remove all registered navigation listeners | | `setOn[EventName]` | `(listener | null | undefined) => void` | Listener setters for each event (e.g., `setOnArrival`, `setOnRouteChanged`). See [full list](#navigation-listener-setters) | > [!TIP] > To remove a specific listener, pass `null` or `undefined` to its setter: `setOnArrival(null)` ``` -------------------------------- ### Configure NavigationProvider with ToS Options (v0.14.x) Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md In v0.14.x, the NavigationProvider requires `termsAndConditionsDialogOptions`. This includes title, companyName, showOnlyDisclaimer, and optional UI customization. ```tsx // App.tsx - Provider with ToS options (required) import { NavigationProvider, TaskRemovedBehavior, } from '@googlemaps/react-native-navigation-sdk'; {children} ``` -------------------------------- ### Move UI Settings to View Props (0.13.x) Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/MIGRATING.md Before v0.14.x, UI settings for navigation and map views were applied imperatively using controller methods. ```tsx useEffect(() => { navigationViewController?.setSpeedometerEnabled(true); navigationViewController?.setSpeedLimitIconEnabled(true); navigationViewController?.setHeaderEnabled(true); navigationViewController?.setFooterEnabled(true); navigationViewController?.setRecenterButtonEnabled(true); navigationViewController?.setTrafficIncidentCardsEnabled(true); mapViewController?.setMyLocationEnabled(true); mapViewController?.setMyLocationButtonEnabled(true); }, [navigationViewController, mapViewController]); ``` -------------------------------- ### NavigationViewController API Source: https://context7.com/googlemaps/react-native-navigation-sdk/llms.txt Provides methods specific to navigation view control, including route overview and camera following behavior. ```APIDOC ## NavigationViewController ### Description The `NavigationViewController` provides methods specific to navigation view control, including route overview and camera following behavior. ### Methods #### `showRouteOverview()` Displays the entire route on the map. #### `setNavigationUIEnabled(enabled)` Enables or disables the navigation UI. - **enabled** (boolean) - Required - Whether to enable the navigation UI. #### `setFollowingPerspective(perspective, options)` Sets the camera perspective for following the user's movement. - **perspective** (CameraPerspective) - Required - The desired camera perspective. - `CameraPerspective.TILTED`: 3D perspective following user direction. - `CameraPerspective.TOP_DOWN_NORTH_UP`: Top-down view with north at top. - `CameraPerspective.TOP_DOWN_HEADING_UP`: Top-down view facing travel direction. - **options** (object) - Optional - Additional options for the perspective. - **zoomLevel** (number) - Optional - A fixed zoom level to use. ### Request Example ```tsx import { type NavigationViewController, CameraPerspective, } from '@googlemaps/react-native-navigation-sdk'; function navViewOperations(navViewController: NavigationViewController) { navViewController.showRouteOverview(); navViewController.setNavigationUIEnabled(true); navViewController.setFollowingPerspective(CameraPerspective.TILTED); navViewController.setFollowingPerspective(CameraPerspective.TOP_DOWN_HEADING_UP, { zoomLevel: 18, }); } ``` ``` -------------------------------- ### Create a New Branch Source: https://github.com/googlemaps/react-native-navigation-sdk/blob/main/CONTRIBUTING.md Fetch upstream changes and create a new branch for your contributions based on the master branch. ```bash git fetch upstream git checkout upstream/master -b ```