### Install @react-native-community/geolocation Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Instructions for adding the Geolocation module to your React Native project using either yarn or npm package managers. ```bash yarn add @react-native-community/geolocation ``` ```bash npm install @react-native-community/geolocation --save ``` -------------------------------- ### Get Current Geolocation Information in React Native Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Provides a basic example of how to retrieve the device's current geographical position using the `getCurrentPosition` method from the `Geolocation` module. It logs the position information to the console. ```javascript import Geolocation from '@react-native-community/geolocation'; Geolocation.getCurrentPosition(info => console.log(info)); ``` -------------------------------- ### Get Current Position with Options Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Shows how to call `getCurrentPosition` with optional parameters to control the timeout, maximum age of cached positions, and whether to enable high accuracy (GPS). ```typescript Geolocation.getCurrentPosition( position => { console.log(position); }, error => { console.error(error); }, { timeout: 10000, maximumAge: 0, enableHighAccuracy: true } ); ``` -------------------------------- ### Web Platform Support for Geolocation in React Native Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt This snippet demonstrates how to use the Geolocation API on the web platform within a React Native project. It leverages the browser's native navigator.geolocation API and shows examples of getCurrentPosition and watchPosition. Note that some React Native-specific features are not available on web. ```javascript import Geolocation from '@react-native-community/geolocation'; import { Platform } from 'react-native'; if (Platform.OS === 'web') { // Standard web API methods work Geolocation.getCurrentPosition( (position) => { console.log('Web location:', position.coords); }, (error) => { console.error('Web location error:', error); }, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 } ); // Watch position also works on web const watchId = Geolocation.watchPosition( (pos) => console.log('Web position update:', pos.coords) ); Geolocation.clearWatch(watchId); // These methods throw errors on web: // Geolocation.setRNConfiguration() - Not supported // Geolocation.requestAuthorization() - Not supported } // Cross-platform browser polyfill (for web compatibility) if (Platform.OS === 'web') { navigator.geolocation = require('@react-native-community/geolocation'); } ``` -------------------------------- ### Get Current Device Location with @react-native-community/geolocation Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Retrieves the device's current geographic position once. It accepts success and error callbacks, along with configuration options for accuracy, timeout, and cache age. The position data includes coordinates, accuracy, altitude, heading, and speed. Error handling covers permission denial, unavailability, and timeouts. ```javascript import Geolocation from '@react-native-community/geolocation'; import { Alert } from 'react-native'; // Get current position with high accuracy Geolocation.getCurrentPosition( (position) => { const { latitude, longitude, accuracy, altitude, heading, speed } = position.coords; const timestamp = position.timestamp; console.log('Current Location:', { latitude: latitude, longitude: longitude, accuracy: `${accuracy} meters`, altitude: altitude ? `${altitude} meters` : 'unavailable', heading: heading ? `${heading} degrees` : 'unavailable', speed: speed ? `${speed} m/s` : 'unavailable', timestamp: new Date(timestamp).toLocaleString() }); // Example output: // { // latitude: 37.7749, // longitude: -122.4194, // accuracy: "10 meters", // altitude: "15 meters", // heading: "180 degrees", // speed: "0 m/s", // timestamp: "1/9/2026, 10:30:00 AM" // } }, (error) => { // Error codes: PERMISSION_DENIED (1), POSITION_UNAVAILABLE (2), TIMEOUT (3) Alert.alert('Location Error', `Code ${error.code}: ${error.message}`); if (error.code === error.PERMISSION_DENIED) { console.log('User denied location permission'); } else if (error.code === error.TIMEOUT) { console.log('Location request timed out'); } else if (error.code === error.POSITION_UNAVAILABLE) { console.log('Location services unavailable'); } }, { enableHighAccuracy: true, // Use GPS for higher accuracy timeout: 15000, // Wait up to 15 seconds maximumAge: 10000 // Accept cached position up to 10 seconds old } ); ``` -------------------------------- ### Stop Location Monitoring with clearWatch (React Native) Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Stops a location watch observer previously started with `watchPosition()`. Each active watch observer has a unique ID, and `clearWatch()` requires this ID to stop the specific observer. It's safe to call `clearWatch` with an invalid or already cleared ID, as it will be silently ignored. ```javascript import Geolocation from '@react-native-community/geolocation'; // Start multiple location watchers const watchId1 = Geolocation.watchPosition( (pos) => console.log('Watcher 1:', pos.coords), (err) => console.error('Watcher 1 error:', err), { distanceFilter: 50 } ); const watchId2 = Geolocation.watchPosition( (pos) => console.log('Watcher 2:', pos.coords), (err) => console.error('Watcher 2 error:', err), { enableHighAccuracy: true } ); console.log('Active watch IDs:', watchId1, watchId2); // Stop specific watcher Geolocation.clearWatch(watchId1); console.log('Cleared watch ID:', watchId1); // Stop all watchers Geolocation.clearWatch(watchId1); Geolocation.clearWatch(watchId2); // Safe to call with invalid ID (silently ignored) Geolocation.clearWatch(99999); ``` -------------------------------- ### Migrate from Core React Native Geolocation to Community Module Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Demonstrates how to update existing code that uses the core React Native Geolocation API to use the community module. This involves changing import statements and method calls. ```javascript import Geolocation from '@react-native-community/geolocation'; Geolocation.setRNConfiguration(config); ``` -------------------------------- ### Manual Linking for React Native < 0.65 (Android) Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Provides steps for manually linking the geolocation module in older React Native projects (prior to version 0.65) on Android. This involves modifying settings.gradle, app/build.gradle, and MainApplication.java. ```java android/settings.gradle include ':react-native-community-geolocation' project(':react-native-community-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/geolocation/android') ``` ```java android/app/build.gradle dependencies { ... implementation project(':react-native-community-geolocation') } ``` ```java android/app/src/main/.../MainApplication.java On imports section: import com.reactnativecommunity.geolocation.GeolocationPackage; In the class at getPackages method: @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: packages.add(new GeolocationPackage()); // <== add this line return packages; } ``` -------------------------------- ### Configure React Native Geolocation Module Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Illustrates how to set global configuration options for the Geolocation module using `setRNConfiguration`. This method accepts an object with properties like `skipPermissionRequests`, `authorizationLevel`, `enableBackgroundLocationUpdates`, and `locationProvider`. ```typescript Geolocation.setRNConfiguration({ skipPermissionRequests: false, authorizationLevel: 'always', enableBackgroundLocationUpdates: true, locationProvider: 'playServices' }); ``` -------------------------------- ### Add Community Geolocation as Browser Polyfill in React Native Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Shows how to make the community Geolocation module available globally as `navigator.geolocation` in React Native applications. This is useful for cross-platform compatibility and backward compatibility. ```javascript navigator.geolocation = require('@react-native-community/geolocation'); ``` -------------------------------- ### Request Geolocation Authorization Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Demonstrates the usage of the `requestAuthorization` method to prompt the user for location permissions. It includes optional success and error callback functions to handle the outcome of the authorization request. ```typescript Geolocation.requestAuthorization( () => { console.log('Authorization granted'); }, (error) => { console.error('Authorization error:', error); } ); ``` -------------------------------- ### Android Geolocation Permissions Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md Specifies the necessary permissions to be added to the AndroidManifest.xml file for accessing location services. Includes options for fine and coarse location. ```xml ``` ```xml ``` -------------------------------- ### Configure Location Services with setRNConfiguration Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Sets global configuration options for location requests. Supports platform-specific settings for iOS and Android, including permission handling, location provider selection, and background updates. Manual permission management is also supported. ```javascript import Geolocation from '@react-native-community/geolocation'; import { Platform, PermissionsAndroid } from 'react-native'; // iOS Configuration if (Platform.OS === 'ios') { Geolocation.setRNConfiguration({ skipPermissionRequests: false, // Auto-request permissions authorizationLevel: 'whenInUse', // 'whenInUse', 'always', or 'auto' enableBackgroundLocationUpdates: true // Enable background location tracking }); } // Android Configuration if (Platform.OS === 'android') { Geolocation.setRNConfiguration({ skipPermissionRequests: false, locationProvider: 'playServices' // 'playServices', 'android', or 'auto' }); // 'playServices' - Use Google Play Services Location API (recommended) // 'android' - Use standard Android Location API // 'auto' - Try Play Services, fallback to Android API } // Manual Permission Management Geolocation.setRNConfiguration({ skipPermissionRequests: true // Handle permissions manually using PermissionsAndroid }); // Then request permissions manually before using location APIs async function requestLocationPermission() { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Location Permission', message: 'App needs access to your location', buttonPositive: 'OK' } ); return granted === PermissionsAndroid.RESULTS.GRANTED; } return true; } await requestLocationPermission(); Geolocation.getCurrentPosition( (pos) => console.log(pos), (err) => console.error(err) ); ``` -------------------------------- ### setRNConfiguration - Configure Location Services Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Sets global configuration options for location services. This allows fine-tuning of permission handling, location provider selection, and background location updates for both iOS and Android platforms. ```APIDOC ## setRNConfiguration ### Description Sets global configuration options that apply to all subsequent location requests. Platform-specific options allow fine-tuning of permission handling, location provider selection, and background location updates. ### Method `setRNConfiguration` ### Parameters #### Request Body - **skipPermissionRequests** (boolean) - Optional - If true, permissions must be handled manually. Defaults to false. - **authorizationLevel** (string) - Optional (iOS only) - Specifies when location permissions are requested. Can be 'whenInUse', 'always', or 'auto'. - **enableBackgroundLocationUpdates** (boolean) - Optional (iOS only) - Enables background location tracking. Defaults to false. - **locationProvider** (string) - Optional (Android only) - Selects the location provider. Can be 'playServices' (recommended), 'android', or 'auto'. ### Request Example ```javascript // iOS Configuration if (Platform.OS === 'ios') { Geolocation.setRNConfiguration({ skipPermissionRequests: false, authorizationLevel: 'whenInUse', enableBackgroundLocationUpdates: true }); } // Android Configuration if (Platform.OS === 'android') { Geolocation.setRNConfiguration({ skipPermissionRequests: false, locationProvider: 'playServices' }); } // Manual Permission Management Geolocation.setRNConfiguration({ skipPermissionRequests: true }); ``` ### Response This method does not return a value but configures the library's behavior. ``` -------------------------------- ### Monitor Location Changes with watchPosition (React Native) Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Continuously monitors the device's location and invokes a success callback upon changes. It returns a watch ID for stopping the monitoring and supports advanced options for battery optimization like distance filtering and update intervals. This method is suitable for real-time tracking applications. ```javascript import { useState, useEffect } from 'react'; import Geolocation from '@react-native-community/geolocation'; import { Alert } from 'react-native'; function LocationTracker() { const [watchId, setWatchId] = useState(null); const [currentPosition, setCurrentPosition] = useState(null); const startTracking = () => { const id = Geolocation.watchPosition( (position) => { setCurrentPosition({ latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, speed: position.coords.speed, timestamp: position.timestamp }); console.log('Position updated:', position.coords); }, (error) => { Alert.alert('Watch Error', `${error.code}: ${error.message}`); }, { enableHighAccuracy: true, distanceFilter: 10, // Only update when moved 10+ meters interval: 5000, // Android: prefer updates every 5 seconds fastestInterval: 2000, // Android: handle updates as fast as 2 seconds useSignificantChanges: false // iOS: use continuous updates, not significant changes } ); setWatchId(id); console.log('Started watching position with ID:', id); }; const stopTracking = () => { if (watchId !== null) { Geolocation.clearWatch(watchId); setWatchId(null); console.log('Stopped watching position'); } }; // Clean up on unmount useEffect(() => { return () => { if (watchId !== null) { Geolocation.clearWatch(watchId); } }; }, [watchId]); return { currentPosition, startTracking, stopTracking, isTracking: watchId !== null }; } // Usage const tracker = LocationTracker(); tracker.startTracking(); // Begin monitoring // ... later tracker.stopTracking(); // Stop monitoring ``` -------------------------------- ### TypeScript Type Definitions for Geolocation API Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt This snippet showcases the TypeScript type definitions provided by the library, enabling type safety and autocompletion for geolocation-related operations. It demonstrates type-safe handling of position data, errors, options, and configuration objects. ```typescript import Geolocation, { GeolocationResponse, GeolocationError, GeolocationOptions, GeolocationConfiguration } from '@react-native-community/geolocation'; // Type-safe position handling const handlePosition = (position: GeolocationResponse): void => { const coords: { latitude: number; longitude: number; altitude: number | null; accuracy: number; altitudeAccuracy: number | null; heading: number | null; speed: number | null; } = position.coords; const timestamp: number = position.timestamp; console.log(`Location: ${coords.latitude}, ${coords.longitude}`); }; // Type-safe error handling const handleError = (error: GeolocationError): void => { const code: number = error.code; const message: string = error.message; // Error code constants const PERMISSION_DENIED: number = error.PERMISSION_DENIED; // 1 const POSITION_UNAVAILABLE: number = error.POSITION_UNAVAILABLE; // 2 const TIMEOUT: number = error.TIMEOUT; // 3 console.error(`Error ${code}: ${message}`); }; // Type-safe options const options: GeolocationOptions = { timeout: 20000, maximumAge: 5000, enableHighAccuracy: true, distanceFilter: 25, useSignificantChanges: false, interval: 10000, fastestInterval: 5000 }; // Type-safe configuration const config: GeolocationConfiguration = { skipPermissionRequests: false, authorizationLevel: 'whenInUse', locationProvider: 'playServices', enableBackgroundLocationUpdates: true }; Geolocation.setRNConfiguration(config); Geolocation.getCurrentPosition(handlePosition, handleError, options); ``` -------------------------------- ### Watch Geolocation Updates with watchPosition Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md The `watchPosition` method invokes a success callback whenever the device's location changes. It accepts a success callback, an optional error callback, and an options object to configure update frequency, accuracy, and filtering. It returns a `watchId` (number) used to clear the watch. ```typescript Geolocation.watchPosition( success: (position: { coords: { latitude: number; longitude: number; altitude: number | null; accuracy: number; altitudeAccuracy: number | null; heading: number | null; speed: number | null; }; timestamp: number; }) => void, error?: (error: { code: number; message: string; PERMISSION_DENIED: number; POSITION_UNAVAILABLE: number; TIMEOUT: number; }) => void, options?: { interval?: number; fastestInterval?: number; timeout?: number; maximumAge?: number; enableHighAccuracy?: boolean; distanceFilter?: number; useSignificantChanges?: boolean; } ) => number ``` -------------------------------- ### Request Location Permissions with requestAuthorization Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Explicitly requests location permissions from the user. On iOS, the permission level is determined by Info.plist. On Android API 23+, this should be used with PermissionsAndroid. Provides callbacks for success and error handling. ```javascript import Geolocation from '@react-native-community/geolocation'; import { Alert, Platform, PermissionsAndroid } from 'react-native'; // Request authorization before accessing location Geolocation.requestAuthorization( () => { console.log('Location permission granted'); // Now safe to request location Geolocation.getCurrentPosition( (position) => { console.log('Location retrieved:', position.coords); }, (error) => { console.error('Location error:', error); } ); }, (error) => { // Error codes: PERMISSION_DENIED, POSITION_UNAVAILABLE, TIMEOUT Alert.alert( 'Permission Denied', `Unable to access location: ${error.message}`, [{ text: 'OK' }] ); if (error.code === error.PERMISSION_DENIED) { console.log('User denied permission - guide them to settings'); } } ); // Full Android example with manual permission handling async function setupLocationAccess() { if (Platform.OS === 'android' && Platform.Version >= 23) { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ); if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log('Android permission granted'); return true; } else { console.log('Android permission denied'); return false; } } catch (err) { console.error('Permission request error:', err); return false; } } else { // iOS or older Android return new Promise((resolve) => { Geolocation.requestAuthorization( () => resolve(true), () => resolve(false) ); }); } } // Usage const hasPermission = await setupLocationAccess(); if (hasPermission) { Geolocation.getCurrentPosition( (pos) => console.log('Success:', pos), (err) => console.error('Error:', err) ); } ``` -------------------------------- ### requestAuthorization - Request Location Permissions Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Explicitly requests location permissions from the user. This method is crucial for managing user consent for accessing location data, especially on iOS and Android API 23+. ```APIDOC ## requestAuthorization ### Description Explicitly requests location permissions from the user. On iOS, the permission level (always vs when-in-use) depends on the Info.plist configuration. On Android API 23+, this should be used in conjunction with the PermissionsAndroid API for a robust permission flow. ### Method `requestAuthorization` ### Parameters This method accepts two callback functions: - **successCallback** (function) - Called when permission is granted. Receives no arguments. - **errorCallback** (function) - Called when permission is denied or an error occurs. Receives an error object with properties like `code` (e.g., PERMISSION_DENIED, POSITION_UNAVAILABLE, TIMEOUT) and `message`. ### Request Example ```javascript Geolocation.requestAuthorization( () => { console.log('Location permission granted'); // Proceed to get location Geolocation.getCurrentPosition(pos => console.log(pos), err => console.error(err)); }, (error) => { console.error('Location permission error:', error.message); // Handle permission denial or other errors } ); // Android example with manual permission handling async function setupLocationAccess() { if (Platform.OS === 'android' && Platform.Version >= 23) { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ); return granted === PermissionsAndroid.RESULTS.GRANTED; } catch (err) { console.error('Permission request error:', err); return false; } } else { return new Promise((resolve) => { Geolocation.requestAuthorization( () => resolve(true), () => resolve(false) ); }); } } const hasPermission = await setupLocationAccess(); if (hasPermission) { Geolocation.getCurrentPosition(pos => console.log('Success:', pos), err => console.error('Error:', err)); } ``` ### Response This method does not return a value directly but invokes the provided success or error callbacks based on the user's action and platform. ``` -------------------------------- ### getCurrentPosition Source: https://context7.com/michalchudziak/react-native-geolocation/llms.txt Retrieves the device's current geographic position once with configurable accuracy and timeout options. This method is essential for obtaining a single snapshot of the user's location. ```APIDOC ## GET /geolocation/currentPosition ### Description Retrieves the device's current geographic position once with configurable accuracy and timeout options. It accepts success and error callbacks, along with an optional configuration object. ### Method GET (conceptual, actual implementation uses module method) ### Endpoint @react-native-community/geolocation ### Parameters #### Callback Parameters - **successCallback** (function) - Required - Function to execute when the position is successfully retrieved. It receives a `position` object. - **errorCallback** (function) - Optional - Function to execute when an error occurs. It receives an `error` object. #### Configuration Options (object, passed as third argument to `getCurrentPosition`) - **enableHighAccuracy** (boolean) - Optional - Defaults to `false`. If `true`, the device will attempt to use GPS for higher accuracy. - **timeout** (number) - Optional - Defaults to `0` (no timeout). The maximum time in milliseconds to wait for a location. - **maximumAge** (number) - Optional - Defaults to `0`. The maximum age in milliseconds of a cached position that is acceptable. ### Request Example ```javascript import Geolocation from '@react-native-community/geolocation'; Geolocation.getCurrentPosition( (position) => { // Handle successful position retrieval console.log(position); }, (error) => { // Handle error console.error(error); }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 } ); ``` ### Response #### Success Response (Callback Parameter: `position`) - **coords** (object) - Contains the location coordinates. - **latitude** (number) - The latitude of the position. - **longitude** (number) - The longitude of the position. - **accuracy** (number) - The accuracy of the position in meters. - **altitude** (number) - The altitude of the position in meters (may be null). - **heading** (number) - The heading of the device in degrees (may be null). - **speed** (number) - The speed of the device in meters per second (may be null). - **timestamp** (number) - The time at which the position was determined, specified as a JavaSript Number representing the number of milliseconds elapsed since the ECMAScript epoch. - **mocked** (boolean) - Indicates if the position was mocked. - **isFromMockProvider** (boolean) - Indicates if the position came from a mock provider. #### Error Response (Callback Parameter: `error`) - **code** (number) - The error code. - `1`: PERMISSION_DENIED - `2`: POSITION_UNAVAILABLE - `3`: TIMEOUT - **message** (string) - A message describing the error. #### Response Example (Success) ```json { "coords": { "latitude": 37.7749, "longitude": -122.4194, "accuracy": 10, "altitude": 15, "heading": 180, "speed": 0 }, "timestamp": 1678886400000, "mocked": false, "isFromMockProvider": false } ``` #### Response Example (Error) ```json { "code": 1, "message": "The permission checker has denied the permission." } ``` ``` -------------------------------- ### Clear Geolocation Watch with clearWatch Source: https://github.com/michalchudziak/react-native-geolocation/blob/master/README.md The `clearWatch` method is used to stop receiving location updates that were initiated by `watchPosition`. It requires the `watchId` (number) that was returned when `watchPosition` was initially called. ```typescript Geolocation.clearWatch(watchID: number); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.