Location Services
Learn to access device location services and implement location-based features in React Native applications. This is a foundational concept in cross-platform mobile development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React Native experience. Take your time with each section and practice the examples
Location Services Overview
Access device GPS and location services to get current position, watch position changes, and implement location-based features in your React Native app.. This is an essential concept that every React Native developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Location Permissions
Handle location permissions for both iOS and Android. Request appropriate permission level (when in use vs always) based on your app's needs.. This is an essential concept that every React Native developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Location Accuracy
Configure location accuracy and update frequency based on your app's requirements. Balance accuracy with battery usage for optimal user experience.. This is an essential concept that every React Native developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Location Services Example
import React, { useState, useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Alert,
PermissionsAndroid,
Platform
} from 'react-native';
import Geolocation from '@react-native-community/geolocation';
const LocationServices = () => {
const [location, setLocation] = useState(null);
const [watching, setWatching] = useState(false);
const [watchId, setWatchId] = useState(null);
// Request location permission for Android
const requestLocationPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'App needs access to location to show your current position',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
}
return true;
};
const getCurrentLocation = async () => {
const hasPermission = await requestLocationPermission();
if (!hasPermission) {
Alert.alert('Permission denied', 'Location permission is required');
return;
}
Geolocation.getCurrentPosition(
(position) => {
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
timestamp: position.timestamp,
});
},
(error) => {
console.log('Location error:', error);
Alert.alert('Location Error', error.message);
},
{
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
}
);
};
const startWatchingLocation = async () => {
const hasPermission = await requestLocationPermission();
if (!hasPermission) {
Alert.alert('Permission denied', 'Location permission is required');
return;
}
const id = Geolocation.watchPosition(
(position) => {
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
timestamp: position.timestamp,
});
},
(error) => {
console.log('Watch location error:', error);
Alert.alert('Location Error', error.message);
},
{
enableHighAccuracy: true,
distanceFilter: 10, // Update every 10 meters
}
);
setWatchId(id);
setWatching(true);
};
const stopWatchingLocation = () => {
if (watchId) {
Geolocation.clearWatch(watchId);
setWatchId(null);
setWatching(false);
}
};
const clearLocation = () => {
setLocation(null);
};
useEffect(() => {
return () => {
if (watchId) {
Geolocation.clearWatch(watchId);
}
};
}, [watchId]);
const formatTimestamp = (timestamp) => {
return new Date(timestamp).toLocaleString();
};
return (
<View style={styles.container}>
<Text style={styles.title}>Location Services</Text>
{location ? (
<View style={styles.locationContainer}>
<Text style={styles.locationTitle}>Current Location</Text>
<View style={styles.locationInfo}>
<Text style={styles.locationText}>
Latitude: {location.latitude.toFixed(6)}
</Text>
<Text style={styles.locationText}>
Longitude: {location.longitude.toFixed(6)}
</Text>
<Text style={styles.locationText}>
Accuracy: {location.accuracy.toFixed(2)} meters
</Text>
<Text style={styles.locationText}>
Time: {formatTimestamp(location.timestamp)}
</Text>
</View>
</View>
) : (
<View style={styles.placeholderContainer}>
<Text style={styles.placeholderText}>No location data</Text>
</View>
)}
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={getCurrentLocation}>
<Text style={styles.buttonText}>📍 Get Current Location</Text>
</TouchableOpacity>
{!watching ? (
<TouchableOpacity style={styles.button} onPress={startWatchingLocation}>
<Text style={styles.buttonText}>👁️ Watch Location</Text>
</TouchableOpacity>
) : (
<TouchableOpacity style={[styles.button, styles.stopButton]} onPress={stopWatchingLocation}>
<Text style={styles.buttonText}>⏹️ Stop Watching</Text>
</TouchableOpacity>
)}
{location && (
<TouchableOpacity style={[styles.button, styles.clearButton]} onPress={clearLocation}>
<Text style={styles.buttonText}>🗑️ Clear Location</Text>
</TouchableOpacity>
)}
</View>
{watching && (
<View style={styles.watchingContainer}>
<Text style={styles.watchingText}>👁️ Watching location changes...</Text>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 30,
color: '#333',
},
locationContainer: {
backgroundColor: 'white',
padding: 20,
borderRadius: 8,
marginBottom: 30,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
},
locationTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 15,
textAlign: 'center',
},
locationInfo: {
gap: 8,
},
locationText: {
fontSize: 14,
color: '#666',
},
placeholderContainer: {
height: 150,
backgroundColor: 'white',
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 30,
},
placeholderText: {
fontSize: 16,
color: '#999',
},
buttonContainer: {
gap: 15,
},
button: {
backgroundColor: '#2196F3',
padding: 15,
borderRadius: 8,
alignItems: 'center',
},
stopButton: {
backgroundColor: '#ff9800',
},
clearButton: {
backgroundColor: '#f44336',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
watchingContainer: {
backgroundColor: '#e3f2fd',
padding: 15,
borderRadius: 8,
marginTop: 20,
alignItems: 'center',
},
watchingText: {
fontSize: 14,
color: '#1976d2',
fontWeight: '500',
},
});
export default LocationServices;