How to Use Geolocation in React Native: Simple Guide
In React Native, you can use the
Geolocation API from @react-native-community/geolocation or the built-in navigator.geolocation to get the user's current location. Request permission first, then call getCurrentPosition to retrieve latitude and longitude coordinates.Syntax
The main method to get the current location is getCurrentPosition(successCallback, errorCallback, options).
- successCallback: function called with position data.
- errorCallback: function called if location fails.
- options: optional settings like accuracy and timeout.
Example usage:
navigator.geolocation.getCurrentPosition(
position => { /* use position.coords.latitude and longitude */ },
error => { /* handle error */ },
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);javascript
navigator.geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords;
console.log('Latitude:', latitude, 'Longitude:', longitude);
},
error => {
console.error('Error getting location:', error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);Output
Latitude: 37.4219983 Longitude: -122.084
Example
This example shows a simple React Native component that requests location permission and displays the current latitude and longitude on screen.
javascript
import React, { useEffect, useState } from 'react'; import { View, Text, Button, PermissionsAndroid, Platform } from 'react-native'; export default function LocationExample() { const [location, setLocation] = useState(null); const [errorMsg, setErrorMsg] = useState(null); const requestLocationPermission = async () => { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ); return granted === PermissionsAndroid.RESULTS.GRANTED; } return true; // iOS permissions handled automatically }; const getLocation = async () => { const hasPermission = await requestLocationPermission(); if (!hasPermission) { setErrorMsg('Location permission denied'); return; } navigator.geolocation.getCurrentPosition( position => { setLocation(position.coords); setErrorMsg(null); }, error => { setErrorMsg(error.message); }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 } ); }; useEffect(() => { getLocation(); }, []); return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> {location ? ( <Text>Latitude: {location.latitude}\nLongitude: {location.longitude}</Text> ) : errorMsg ? ( <Text>Error: {errorMsg}</Text> ) : ( <Text>Getting location...</Text> )} <Button title="Refresh Location" onPress={getLocation} /> </View> ); }
Output
Text on screen: "Latitude: 37.4219983\nLongitude: -122.084" or error message if permission denied or location fails.
Common Pitfalls
- Not requesting location permission before accessing location causes failure.
- Using
navigator.geolocationwithout linking or installing@react-native-community/geolocationin newer React Native versions. - Ignoring platform differences: Android requires runtime permission requests, iOS requires entries in
Info.plist. - Not handling errors or timeouts leads to poor user experience.
javascript
/* Wrong: No permission request on Android */ navigator.geolocation.getCurrentPosition( pos => console.log(pos.coords), err => console.error(err), { enableHighAccuracy: true } ); /* Right: Request permission first (Android) */ import { PermissionsAndroid, Platform } from 'react-native'; async function getLocation() { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ); if (granted !== PermissionsAndroid.RESULTS.GRANTED) { console.log('Permission denied'); return; } } navigator.geolocation.getCurrentPosition( pos => console.log(pos.coords), err => console.error(err), { enableHighAccuracy: true } ); }
Quick Reference
| Method | Description |
|---|---|
getCurrentPosition | Get current location once |
watchPosition | Track location changes continuously |
clearWatch | Stop tracking location |
| Permissions | Request runtime permissions on Android |
| Options | enableHighAccuracy, timeout, maximumAge |
| Method | Description |
|---|---|
| getCurrentPosition | Get current location once |
| watchPosition | Track location changes continuously |
| clearWatch | Stop tracking location |
| Permissions | Request runtime permissions on Android |
| Options | enableHighAccuracy, timeout, maximumAge |
Key Takeaways
Always request location permission before accessing geolocation on Android.
Use navigator.geolocation.getCurrentPosition to get the user's current location.
Handle errors and timeouts to improve user experience.
Remember to add necessary permissions in AndroidManifest.xml and Info.plist.
Consider using @react-native-community/geolocation for better support in newer React Native versions.