React Native Geolocation Complete Tutorial

Master location tracking in React Native with practical examples for Expo and bare workflows. From permissions to background tracking with performance optimization.

Introduction

Location-based features have become essential in modern mobile applications. From ride-sharing and delivery apps to fitness trackers and location-aware social platforms, geolocation functionality powers countless use cases. React Native provides robust tools to implement these features efficiently, allowing developers to build cross-platform mobile applications with native-level location capabilities.

This comprehensive tutorial will guide you through implementing geolocation in React Native, covering everything from basic setup to advanced tracking scenarios with performance optimization in mind. Whether you're building a navigation app, a fitness tracker, or a location-based service, you'll find practical guidance for every stage of implementation.

The geolocation capabilities in React Native have matured significantly, with the ecosystem now offering well-established packages that handle the complexity of cross-platform location tracking. Modern location APIs provide configurable accuracy levels, efficient background tracking, and seamless integration with map visualization libraries, enabling developers to create sophisticated location-aware experiences without sacrificing battery life or user privacy. Our mobile development services team regularly implements these features for clients across various industries, from logistics and transportation to health and fitness applications.

Getting Started with React Native Geolocation

Understanding the Geolocation Landscape in React Native

React Native doesn't include built-in geolocation support in newer versions, which means developers must choose from several well-established packages depending on their workflow and requirements. The ecosystem offers solutions for both Expo managed workflow and bare React Native CLI approaches, each with distinct advantages, as documented by LogRocket's geolocation fundamentals.

For Expo projects, the recommended approach uses expo-location, which provides a unified API across platforms with minimal configuration overhead. This package handles permission requests automatically and integrates seamlessly with other Expo services. For bare React Native projects, react-native-geolocation-service offers highly accurate location tracking with better reliability on Android devices, particularly when working with Google Play Services, as noted in the Djamware package comparison guide.

The choice between these approaches depends on your project requirements. Expo provides faster setup and is ideal for rapid prototyping, while bare React Native offers deeper native-level control for production applications requiring advanced location features. Understanding this distinction early in your development process will save significant refactoring time later.

Setting Up Your Development Environment

Before implementing geolocation features, ensure your development environment is properly configured. For Expo projects, you'll need to install the expo-location package alongside react-native-maps for map visualization. The installation process is straightforward and managed by Expo's tooling, which automatically resolves compatible versions.

For bare React Native projects, the setup requires additional steps including native dependency linking and platform-specific configuration. You'll need to install react-native-maps, react-native-geolocation-service, and react-native-permissions for handling location authorization requests. iOS projects require CocoaPods installation and proper Info.plist configuration, while Android projects need manifest permissions and Google Maps API key setup.

Testing on physical devices remains essential for accurate location accuracy verification, particularly for GPS-dependent features. iOS Simulator offers location simulation capabilities through the Debug menu, while Android Emulator provides location controls through the extended controls panel.

Recommended Geolocation Packages

Choose the right package for your workflow and requirements

expo-location

Unified API for Expo projects with automatic permission handling and seamless integration with Expo services

react-native-geolocation-service

High-accuracy location tracking for bare React Native with better Android reliability and Google Play Services support

react-native-maps

Cross-platform map rendering with support for markers, polylines, and custom overlays

react-native-permissions

Unified permission handling for bare React Native projects across multiple platform APIs

Requesting Location Permissions

Understanding Platform Permission Models

Location permissions operate differently across iOS and Android platforms, requiring careful attention to ensure proper authorization flows. iOS requires explicit user permission declared in Info.plist with a usage description explaining why location access is needed, as detailed in LogRocket's iOS permissions guide. The system offers two permission levels: when-in-use and always, with always requiring additional justification and review during App Store submission.

Android's permission model has evolved significantly, now requiring runtime permission requests in addition to manifest declarations. Android 10 and later introduced background location restrictions, requiring separate permission grants for apps needing location access when not actively in use, as documented by Djamware's Android permissions overview. Understanding these platform differences is crucial for building applications that function correctly across the full range of supported devices.

The permission request flow should be implemented gracefully, providing clear explanations to users about why location access benefits their experience. Apps that fail to communicate the value proposition of location access often see lower permission grant rates, impacting feature adoption and user satisfaction, as noted by DevsTree's user communication research.

Implementing Permission Requests

For Expo projects, requesting foreground permissions uses the requestForegroundPermissionsAsync method, which returns a grant status indicating whether the user authorized location access. The API handles the platform-specific dialog presentation and user interaction automatically, simplifying the implementation significantly.

Expo Permission Request:

const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
 // Handle permission denial - provide clear explanation to user
 console.log('Location permission denied');
 return;
}

Bare React Native projects require manual permission handling using react-native-permissions or platform-specific APIs. Android projects use the PermissionsAndroid API to request runtime permissions, while iOS projects rely on Info.plist declarations and the native system dialog.

Bare React Native Permission Request:

import { PermissionsAndroid } from 'react-native';

const requestLocationPermission = async () => {
 const granted = await PermissionsAndroid.request(
 PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
 {
 title: 'Location Permission',
 message: 'This app needs access to your location for core features',
 buttonNeutral: 'Ask Me Later',
 buttonNegative: 'Cancel',
 buttonPositive: 'OK'
 }
 );
 return granted === PermissionsAndroid.RESULTS.GRANTED;
};

Background location permissions require additional consideration. iOS requires the NSLocationAlwaysAndWhenInUseUsageDescription key in Info.plist and explicit capability enablement in Xcode. Android requires the ACCESS_BACKGROUND_LOCATION permission declaration, which triggers a separate permission prompt that users must explicitly approve.

Getting the User's Current Location

Single-Position Location Retrieval

Retrieving the user's current position involves calling the appropriate API method and handling the returned coordinates. For Expo projects, getCurrentPositionAsync provides immediate location retrieval with configurable accuracy levels. The method returns a location object containing coordinates, timestamp, and accuracy information, as described in LogRocket's current position documentation.

Expo getCurrentPosition Implementation:

import * as Location from 'expo-location';

const getCurrentLocation = async () => {
 const location = await Location.getCurrentPositionAsync({
 accuracy: Location.Accuracy.High
 });
 
 const { latitude, longitude, accuracy, timestamp } = location.coords;
 return { latitude, longitude, accuracy, timestamp };
};

Bare React Native getCurrentPosition Implementation:

import Geolocation from 'react-native-geolocation-service';

Geolocation.getCurrentPosition(
 (position) => {
 const { latitude, longitude, accuracy } = position.coords;
 console.log('Current position:', latitude, longitude);
 },
 (error) => {
 // Handle errors based on error.code
 switch (error.code) {
 case 1:
 console.log('Permission denied');
 break;
 case 2:
 console.log('Position unavailable');
 break;
 case 3:
 console.log('Timeout');
 break;
 }
 },
 { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);

Configuring Location Accuracy

Location accuracy settings directly impact both the quality of position data and battery consumption, as noted in Medium's battery optimization guide. High accuracy mode uses GPS, Wi-Fi, and cellular triangulation to determine position, providing meter-level precision at the cost of increased power consumption. Low accuracy mode relies primarily on network-based positioning, offering faster fixes with reduced precision.

Accuracy Levels in Expo:

  • Accuracy.Lowest - Lowest power, approximately city-level accuracy
  • Accuracy.Low - Low power, neighborhood-level accuracy
  • Accuracy.Balanced - Balanced between accuracy and power
  • Accuracy.High - Good accuracy with reasonable power
  • Accuracy.Highest - Best accuracy, highest power consumption
  • Accuracy.BestForNavigation - Optimized for navigation use cases

Error handling is essential when retrieving location data. Common error scenarios include permission denial, GPS unavailability, timeout expiration, and network-based location service failures. Implementing robust error handling with user feedback ensures graceful degradation when location services are unavailable, as documented by DevsTree's error handling best practices.

Watching Continuous Location Updates

Implementing Real-Time Location Tracking

Continuous location tracking uses watchPosition methods that invoke callbacks whenever the device detects significant location changes. This approach is essential for features requiring real-time position updates, such as navigation, fitness tracking, and fleet management applications, as documented by LogRocket's position watching guide.

Expo watchPositionAsync Implementation:

import * as Location from 'expo-location';

const startLocationTracking = () => {
 const watchPosition = Location.watchPositionAsync(
 {
 accuracy: Location.Accuracy.High,
 timeInterval: 5000,
 distanceInterval: 10
 },
 (location) => {
 // Update state with new coordinates
 setCurrentLocation({
 latitude: location.coords.latitude,
 longitude: location.coords.longitude,
 accuracy: location.coords.accuracy
 });
 }
 );
 
 return watchPosition;
};

Bare React Native watchPosition Implementation:

import Geolocation from 'react-native-geolocation-service';

const watchId = Geolocation.watchPosition(
 (position) => {
 // Handle position update
 const { latitude, longitude } = position.coords;
 updateLocation(latitude, longitude);
 },
 (error) => {
 if (error.code === 2) {
 // GPS disabled
 enableGPSPrompt();
 }
 },
 {
 enableHighAccuracy: true,
 distanceFilter: 10,
 interval: 5000,
 fastestInterval: 2000
 }
);

Managing Watch Subscriptions

Location watches consume system resources and must be properly cleaned up when no longer needed. React Native's useEffect hook provides the ideal location for watch management, with cleanup functions ensuring subscriptions are terminated when components unmount, as recommended in LogRocket's subscription cleanup guide.

Complete Subscription Management Example:

import { useEffect, useRef, useState } from 'react';
import * as Location from 'expo-location';

const LocationTracker = () => {
 const [location, setLocation] = useState(null);
 const watchRef = useRef(null);

 useEffect(() => {
 const startTracking = async () => {
 const { status } = await Location.requestForegroundPermissionsAsync();
 if (status !== 'granted') return;

 watchRef.current = await Location.watchPositionAsync(
 {
 accuracy: Location.Accuracy.High,
 timeInterval: 5000,
 distanceInterval: 10
 },
 (newLocation) => {
 setLocation(newLocation.coords);
 }
 );
 };

 startTracking();

 return () => {
 if (watchRef.current) {
 watchRef.current.remove();
 }
 };
 }, []);

 return location;
};

Memory leaks and excessive battery consumption can result from improperly managed location watches. Always store watch references and remove them during component unmounting, navigation changes, or feature deactivation. Consider implementing a context provider for centralized location management across your application.

Displaying Location on Maps

Integrating react-native-maps

Map visualization transforms raw coordinates into meaningful geographic context. react-native-maps provides cross-platform map rendering with support for Google Maps on Android and iOS, as well as Apple Maps on iOS. The library offers comprehensive mapping capabilities including markers, polylines, polygons, and custom overlays, as detailed in the Djamware MapView basics guide.

Basic MapView Implementation:

import MapView, { Marker, Polyline } from 'react-native-maps';

const MapComponent = ({ latitude, longitude }) => {
 return (
 <MapView
 style={{ flex: 1 }}
 initialRegion={{
 latitude: latitude,
 longitude: longitude,
 latitudeDelta: 0.0922,
 longitudeDelta: 0.0421
 }}
 showsUserLocation={true}
 showsMyLocationButton={true}
 >
 <Marker
 coordinate={{ latitude, longitude }}
 title="Current Location"
 description="You are here"
 />
 </MapView>
 );
};

Google Maps API keys are required for map functionality on both platforms. Android configuration requires the API key in AndroidManifest.xml, while iOS requires the key in AppDelegate.m or AppDelegate.mm. Without properly configured keys, maps may display blank tiles or grid patterns.

Adding Markers and Polylines

Markers represent specific geographic points on the map and support customization through images, colors, and custom views. The Marker component accepts coordinate, title, description, and draggable props for interactive positioning, as documented in the Djamware markers documentation.

Draggable Marker Example:

<Marker
 coordinate={markerPosition}
 title="Destination"
 description="Estimated arrival location"
 draggable
 onDragEnd={(e) => {
 setMarkerPosition(e.nativeEvent.coordinate);
 }}
/>

Route Polyline Visualization:

<Polyline
 coordinates={routeCoordinates}
 strokeWidth={4}
 strokeColor="#FF5722"
 lineDashPattern={[10, 5]}
/>

For more advanced mapping features, consider our React Native development services which include comprehensive map integration solutions with custom styling, clustering, and advanced marker rendering.

Performance and Battery Optimization

Balancing Accuracy with Battery Life

Location tracking inherently impacts battery consumption, with high-frequency GPS updates representing one of the most power-intensive operations on mobile devices. Understanding the relationship between update frequency, accuracy, and battery impact is essential for building efficient location-aware applications, as documented in Medium's battery impact analysis.

High accuracy mode with frequent updates provides the most precise tracking but drains battery rapidly. For most use cases, balancing accuracy with update frequency based on feature requirements produces optimal results. Fitness tracking during active sessions may warrant high accuracy, while background tracking during commute monitoring should use lower accuracy settings, as recommended by DevsTree's optimization strategies.

High Accuracy Configuration for Active Tracking:

const activeTrackingConfig = {
 accuracy: Location.Accuracy.Highest,
 distanceInterval: 5,
 timeInterval: 2000
};

Battery-Efficient Configuration for Background Tracking:

const backgroundTrackingConfig = {
 accuracy: Location.Accuracy.Low,
 distanceInterval: 50,
 timeInterval: 30000
};

Implementing Intelligent Update Strategies

Adaptive update strategies adjust tracking parameters based on user activity and application state. Moving vehicles warrant more frequent updates than stationary users, while background states should use significantly reduced update frequencies, as outlined in DevsTree's adaptive strategies guide. Our AI automation services can help implement intelligent activity recognition systems that optimize tracking efficiency based on detected user behavior patterns.

Smart Tracking Implementation:

const getTrackingConfig = (isMoving, isBackground) => {
 if (isBackground) {
 return {
 accuracy: Location.Accuracy.Low,
 distanceInterval: 100,
 timeInterval: 60000
 };
 }
 
 if (isMoving) {
 return {
 accuracy: Location.Accuracy.High,
 distanceInterval: 10,
 timeInterval: 5000
 };
 }
 
 // Stationary, foreground
 return {
 accuracy: Location.Accuracy.Balanced,
 distanceInterval: 50,
 timeInterval: 15000
 };
};

Implementing activity recognition, either through dedicated libraries or motion sensors, can further optimize tracking efficiency. Detecting that a device has been stationary for extended periods allows applications to reduce or suspend location updates entirely, preserving battery life without sacrificing tracking accuracy when movement resumes, as noted in Medium's intelligent tracking article.

Batch processing location data reduces the frequency of state updates and API calls. Instead of updating UI for every location change, applications can accumulate positions and update displays at controlled intervals, reducing rendering overhead and network requests, as documented by DevsTree's batch processing techniques.

Battery Impact by Tracking Mode

10x

Battery drain with high-frequency GPS

60%

Battery saved with optimized intervals

50m

Recommended distance filter for efficiency

30s

Optimal time interval for background

Background Location Tracking

Understanding Background Limitations

Both iOS and Android impose strict limitations on background location access to protect user privacy and battery life. iOS requires explicit background mode capabilities and usage descriptions, with the system displaying persistent indicators when apps access location in the background. Android requires separate background permission grants and may restrict background access based on battery optimization settings, as documented in React Native Expert's background limitations guide.

iOS Background Location Requirements:

  • Enable "Background Modes" → "Location updates" in Xcode capabilities
  • Add NSLocationAlwaysAndWhenInUseUsageDescription to Info.plist
  • System displays blue status bar indicator during background tracking
  • App Store review requires justification for always-on access

Android Background Location Requirements:

  • ACCESS_BACKGROUND_LOCATION in AndroidManifest.xml
  • User must manually enable "Allow all the time" in system settings
  • Battery optimization may restrict background access (request whitelist)
  • Foreground service required for continuous tracking on Android 8.0+

Apps must provide clear justification for background location access during App Store review. Apps without legitimate background location requirements should use foreground-only tracking to avoid rejection. Common legitimate use cases include navigation, ride-sharing, fitness tracking, and family locator applications, as noted by DevsTree's background justification research.

Implementing Background Tracking

For Expo projects, background location tracking requires additional configuration through expo-task-manager and expo-location. Tasks must be defined and registered before starting background updates, with proper handling for task execution in terminated states.

Expo Background Task Implementation:

import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';

const BACKGROUND_LOCATION_TASK = 'background-location-task';

TaskManager.defineTask(BACKGROUND_LOCATION_TASK, ({ data, error }) => {
 if (error) {
 console.error('Background location task error:', error);
 return;
 }

 const { locations } = data;
 if (locations && locations.length > 0) {
 const location = locations[locations.length - 1];
 // Process and store the location
 console.log('Background location:', location.coords);
 }
});

const startBackgroundTracking = async () => {
 const { status: foregroundStatus } = await Location.requestForegroundPermissionsAsync();
 if (foregroundStatus !== 'granted') return;

 const { status: backgroundStatus } = await Location.requestBackgroundPermissionsAsync();
 if (backgroundStatus !== 'granted') return;

 await Location.startLocationUpdatesAsync(BACKGROUND_LOCATION_TASK, {
 accuracy: Location.Accuracy.Low,
 showsBackgroundLocationIndicator: true,
 pausesUpdatesAutomatically: true,
 distanceInterval: 50,
 timeInterval: 30000
 });
};

Bare React Native projects can leverage react-native-background-geolocation for comprehensive background tracking with activity recognition, geofencing, and battery-optimized operation. This library handles platform-specific challenges and provides consistent behavior across Android versions, as documented by DevsTree's production tracking guide.

Bare React Native Background Implementation:

import BackgroundGeolocation from 'react-native-background-geolocation';

const configureBackgroundGeolocation = () => {
 BackgroundGeolocation.ready({
 desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_LOW,
 distanceFilter: 50,
 stopTimeout: 5,
 debug: false,
 logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
 startOnBoot: true,
 stopOnTerminate: false,
 locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
 batterySavingMode: true,
 autoSync: true,
 batchSync: true
 });

 BackgroundGeolocation.start();
};

When implementing background tracking, always test thoroughly on both platforms and ensure your app handles edge cases like app termination, device reboots, and permission changes gracefully.

Common Pitfalls and Debugging

Blank Map Screens

Blank or gray map screens typically indicate missing API key configuration. Verify that Google Maps API keys are properly configured in AndroidManifest.xml for Android and AppDelegate for iOS. Ensure the keys have the Maps SDK enabled in the Google Cloud Console, as noted in Djamware's troubleshooting guide.

Debugging Steps for Blank Maps:

  1. Verify API key is correctly placed in both platform configuration files
  2. Check that the Maps SDK is enabled in Google Cloud Console
  3. Confirm the API key has no restrictions or restrictions match your app's bundle ID
  4. Test on a physical device - emulators without Google Play Services cannot render Google Maps

Android emulators without Google Play Services cannot render Google Maps. Use emulator images labeled with Google Play, or test on physical devices for map functionality verification, as documented by DevsTree's emulator issues guide.

Location Permission Issues

Permission denials prevent location access but can be recovered through user education. Provide clear explanations of why location access benefits the user, and offer settings navigation for manual permission grant if initially denied, as recommended in LogRocket's permission handling guide.

Handling Permission Denials:

import { Platform, Linking, Alert } from 'react-native';

const requestLocationPermission = async () => {
 const { status } = await Location.requestForegroundPermissionsAsync();
 
 if (status === 'denied' || status === 'undetermined') {
 Alert.alert(
 'Location Access Needed',
 'This feature requires location access to work properly. Please grant permission in Settings.',
 [
 { text: 'Cancel', style: 'cancel' },
 { 
 text: 'Open Settings', 
 onPress: () => Linking.openSettings() 
 }
 ]
 );
 }
};

Android's runtime permission model requires explicit user interaction. Check permission status before attempting location operations, and handle both granted and denied states gracefully, as documented by Djamware's Android runtime permissions guide.

Accuracy and Performance Problems

Inaccurate location data often results from GPS signal obstruction, particularly indoors or in urban canyons. Implement fallback logic for network-based positioning when GPS signals are unavailable or unreliable, as documented by DevsTree's accuracy issues guide.

Improving Accuracy:

  • Ensure GPS hardware is not obstructed by cases or objects
  • Test outdoors or near windows for better signal reception
  • Use network-based fallback when GPS is unavailable
  • Implement timeout logic for GPS acquisition

Battery drain complaints indicate excessive tracking frequency or improper subscription cleanup. Review tracking configuration parameters and ensure watches are properly terminated when no longer needed, as noted in Medium's battery troubleshooting guide. For complex geolocation requirements, our software development team can help architect and implement production-ready solutions.

Frequently Asked Questions

What is the best geolocation package for Expo projects?

expo-location provides the simplest integration with automatic permission handling and seamless Expo ecosystem integration. It's the recommended choice for Expo managed workflow projects.

How do I reduce battery consumption when tracking location?

Reduce update frequency, use lower accuracy modes when possible, batch updates, and stop tracking when not needed. Consider implementing adaptive tracking based on user activity state.

Why are my maps showing blank screens?

Check that Google Maps API keys are configured in both AndroidManifest.xml and AppDelegate, and that the Maps SDK is enabled in Google Cloud Console. Also ensure you're testing on a device with Google Play Services.

Can I track location when my app is in the background?

Yes, but requires explicit permission configuration, background mode capabilities, and users must grant 'Always' permission. Both iOS and Android have specific requirements for background location access.

What accuracy level should I use for my app?

Use High accuracy for navigation/fitness, Low accuracy for location-based services. Balance accuracy needs with battery impact. Consider making this configurable based on user preferences.

How do I handle location permission denials?

Provide clear value propositions, offer educational messaging, and guide users to settings for manual permission grant. Never spam permission requests as this reduces grant rates.

Conclusion

Implementing geolocation in React Native requires understanding platform-specific requirements, choosing appropriate packages for your workflow, and implementing proper permission handling and resource management. This tutorial has covered the essential concepts from basic location retrieval through advanced tracking scenarios, providing a foundation for building location-aware mobile applications.

Key takeaways include:

  • Package selection based on Expo vs bare React Native workflows determines your configuration complexity and available features
  • Permission handling for both foreground and background location access requires platform-specific implementation and clear user communication
  • Accuracy trade-offs between precision and battery consumption should guide your tracking configuration decisions
  • Resource management through proper watch subscription cleanup prevents memory leaks and excessive battery drain
  • Background tracking with platform-specific considerations ensures reliable operation while respecting user privacy

The geolocation landscape continues to evolve with platform updates and new library releases. Stay current with documentation updates and community best practices to maintain optimal implementation quality as the ecosystem develops.

For teams building location-aware mobile applications, partnering with experienced developers can accelerate development and ensure production-ready implementations. Our mobile app development services include comprehensive geolocation implementation for iOS and Android platforms, from initial architecture through deployment and ongoing optimization.


Sources

  1. LogRocket: React Native Geolocation Complete Tutorial
  2. Djamware: React Native Maps and Geolocation Complete Guide
  3. React Native Expert: Background Geolocation Library Comprehensive Guide
  4. DevsTree: Mastering Location Tracking in React Native
  5. Medium: Track User Location Without Killing Their Battery - A React Native Guide

Ready to Build Location-Aware Mobile Apps?

Our team specializes in React Native development with advanced geolocation features. Let's discuss your project requirements.