Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Native Modules and APIs

Location and Maps

Use expo-location for the device position: foreground and background permissions, accuracy, getCurrentPositionAsync, watchPositionAsync, geocoding, distance math and showing maps.

Maps, delivery tracking, weather, "stores near me": location is one of the most requested device features and one of the most sensitive. Users are right to be careful, and the stores review location usage strictly. expo-location gives you the current position, continuous updates, geocoding and geofencing with one API for iOS and Android.

The module needs a real device, so its code is read-only. The live stand-ins implement the geometry (distance, bearing) and the subscription pattern yourself.

Setup

Terminal
npx expo install expo-location
JSON
{
  "expo": {
    "plugins": [
      ["expo-location", {
        "locationWhenInUsePermission": "Trail Notes shows trails near you.",
        "isAndroidBackgroundLocationEnabled": false
      }]
    ]
  }
}

There are two permission levels:

  • Foreground ("When in use"): while your app is open. Request with requestForegroundPermissionsAsync(). This is enough for almost everything.
  • Background ("Always"): while the app is closed, for tracking a run or geofencing. Request with requestBackgroundPermissionsAsync() after foreground, add locationAlwaysAndWhenInUsePermission text, and expect strict store review plus a persistent notification on Android. Only ask when it is the core feature (Notifications and Background Tasks).

Follow the permission flow from Camera and Image Picker: ask in context, handle denied and canAskAgain.

Getting the current position

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

export function useCurrentPosition() {
  const [coords, setCoords] = useState<Location.LocationObjectCoords | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setError('Location permission was not granted.');
        return;
      }
      const position = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Balanced,
      });
      setCoords(position.coords);
    })();
  }, []);

  return { coords, error };
}

position.coords has latitude, longitude, altitude, accuracy (meters), heading, speed; position.timestamp is in milliseconds. A faster, possibly stale answer is getLastKnownPositionAsync().

Accuracy is a battery trade-off: Lowest/Low (city-level, cheap), Balanced (about 100 m), High (GPS), Highest and BestForNavigation (continuous GPS, power hungry). Pick the lowest level that serves the feature.

Watching the position

TSX
useEffect(() => {
  let subscription: Location.LocationSubscription | undefined;
  (async () => {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') return;
    subscription = await Location.watchPositionAsync(
      { accuracy: Location.Accuracy.High, distanceInterval: 10, timeInterval: 5000 },
      (pos) => setCoords(pos.coords),
    );
  })();
  return () => subscription?.remove();     // always unsubscribe
}, []);

distanceInterval (meters) and timeInterval (ms) limit updates. Forgetting subscription.remove() keeps GPS on and drains the battery. The pattern "subscribe, and return an unsubscribe function" appears in every Expo sensor API, so here it is in miniature:

JS Subscribe and clean up

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Distance and bearing yourself

Expo gives coordinates; distance between two points is math you write (or take from a library). The haversine formula works well for distances on Earth:

JS Distance between coordinates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Sort "trails near me" by this distance, and show it rounded; precision beyond tens of meters is false confidence given GPS error.

JS Nearest places first

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Geocoding

TSX
const results = await Location.geocodeAsync('Bahnhofstrasse 1, Zurich');     // address -> coordinates
const places = await Location.reverseGeocodeAsync({ latitude: 47.3769, longitude: 8.5417 });
// places[0] = { city, street, country, postalCode, ... }

Geocoding uses the platform's service and is rate limited; cache results and call it on user action, not in loops.

Showing a map

Install react-native-maps (npx expo install react-native-maps). It works in Expo Go; Google Maps on Android needs an API key in the config, and Apple Maps on iOS needs none.

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

<MapView
  style={{ flex: 1 }}
  initialRegion={{ latitude: 47.3769, longitude: 8.5417, latitudeDelta: 0.05, longitudeDelta: 0.05 }}
  showsUserLocation
>
  {trails.map((t) => (
    <Marker key={t.id} coordinate={{ latitude: t.lat, longitude: t.lon }} title={t.name} />
  ))}
</MapView>

latitudeDelta/longitudeDelta set the zoom (smaller is closer). showsUserLocation needs the foreground permission. Keep marker counts reasonable (clustering libraries help at hundreds of points). New SDKs also ship expo-maps, a native Apple/Google Maps wrapper; check the SDK docs for its availability in your version.

Privacy and battery

  • Request the minimum accuracy and duration; stop watching when the screen is not visible.
  • Never send raw location to a server without telling the user why.
  • Provide an alternative (type a city name) for users who deny location.
  • Test with the simulator's location tools, then on a real device outdoors.

Common mistakes

  • Asking for background location when foreground is enough.
  • Not removing the watchPositionAsync subscription.
  • Assuming the first position is accurate; check accuracy and wait for a better fix.
  • Treating null altitude, speed or heading as zero.
  • Calling the location APIs without a plugin text, which fails review.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which permission should you request first and for most features?

    Foreground permission is enough while the app is open and is far less intrusive.
  2. 2. What must you do when finished with watchPositionAsync?

    Removing the subscription stops GPS updates and saves battery.
  3. 3. Which accuracy level is the right default for 'places near me'?

    Balanced is about 100 m and cheap; use higher accuracy only when needed.
  4. 4. What does the haversine formula compute?

    It gives the great-circle distance, which is good enough for 'near me' features.

Summary

  • Request foreground permission in context; ask for background only when essential.
  • Use getCurrentPositionAsync for a one-time fix and watchPositionAsync (with cleanup) for tracking.
  • Pick the lowest accuracy that works; compute distances yourself with haversine.
  • Display maps with react-native-maps; geocode sparingly and respect user privacy.

Next: Sensors and Haptics