Lesson 3 of 10
Location & GPS - Foreground & Background
Location access comes in three tiers: foreground (only while app is open), background (while backgrounded - requires explicit permission), and always. Each tier has different use cases, permission flows, and battery impact.
Foreground Location with Watch
import * as Location from 'expo-location';
import { useEffect, useState } from 'react';
interface LocationState {
coords: Location.LocationObjectCoords | null;
heading: number | null;
error: string | null;
isLoading: boolean;
}
export function useCurrentLocation(accuracy = Location.Accuracy.Balanced) {
const [state, setState] = useState<LocationState>({ coords: null, heading: null, error: null, isLoading: true });
useEffect(() => {
let subscription: Location.LocationSubscription | null = null;
(async () => {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setState(s => ({ ...s, error: 'Location permission denied', isLoading: false }));
return;
}
// One-time position (fast)
const current = await Location.getCurrentPositionAsync({ accuracy });
setState(s => ({ ...s, coords: current.coords, isLoading: false }));
// Live updates (continuous, drains battery - use only when needed)
subscription = await Location.watchPositionAsync({ accuracy, timeInterval: 5000, distanceInterval: 10 }, loc => {
setState(s => ({ ...s, coords: loc.coords }));
});
})().catch(err => setState(s => ({ ...s, error: err.message, isLoading: false })));
return () => { subscription?.remove(); };
}, [accuracy]);
return state;
}
// ---- Distance between two coordinates ----
export function distanceKm(lat1: number, lon1: number, lat2: number, lon2: number): number {
const R = 6371;
const dLat = ((lat2 - lat1) * Math.PI) / 180;
const dLon = ((lon2 - lon1) * Math.PI) / 180;
const a = Math.sin(dLat / 2) ** 2 + Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
// ---- Reverse geocoding: coordinates β address ----
async function getAddress(lat: number, lon: number): Promise<string> {
const [place] = await Location.reverseGeocodeAsync({ latitude: lat, longitude: lon });
if (!place) return 'Unknown location';
return [place.street, place.city, place.region].filter(Boolean).join(', ');
}Background Location (Expo Task Manager)
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';
const LOCATION_TASK = 'background-location-task';
// ---- Define the task (must be at top-level, not inside a component) ----
TaskManager.defineTask(LOCATION_TASK, ({ data, error }: { data: unknown; error: unknown }) => {
if (error) { console.error('BG location error:', error); return; }
const { locations } = data as { locations: Location.LocationObject[] };
const latest = locations[locations.length - 1];
// Update your store or send to server
console.log('Background location:', latest.coords);
});
// ---- Start background tracking ----
async function startBackgroundTracking() {
// Requires 'Always' permission (show context dialog first)
const { status } = await Location.requestBackgroundPermissionsAsync();
if (status !== 'granted') return;
await Location.startLocationUpdatesAsync(LOCATION_TASK, {
accuracy: Location.Accuracy.Balanced,
timeInterval: 60_000, // update every minute
distanceInterval: 100, // or when moved 100m
showsBackgroundLocationIndicator: true, // iOS blue bar
foregroundService: {
notificationTitle: 'Tracking your ride',
notificationBody: 'Location is being used to track your route.',
notificationColor: '#229c6b',
},
});
}
async function stopBackgroundTracking() {
await Location.stopLocationUpdatesAsync(LOCATION_TASK);
}Tip
Tip
Practice Location GPS Foreground Background in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
High-accuracy GPS location tracking and background geofencing with TaskManager
Practice Task
Note
Practice Task - (1) Write a working example of Location GPS Foreground Background from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Location GPS Foreground Background is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?