Expo

Get Started
API Reference

Location

expo-location allows reading geolocation information from the device. Your app can poll for the current location or subscribe to location update events.

Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

Installation

expo install expo-location

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

In Managed and bare apps, Location requires Permissions.LOCATION.
In order to use Background Location Methods, the following requirements apply:
  • Permissions.LOCATION permission must be granted. On iOS it must be granted with Always option — see Permissions.LOCATION for more details.
  • "location" background mode must be specified in Info.plist file. See background tasks configuration guide. (iOS only)
  • Background location task must be defined in the top-level scope, using TaskManager.defineTask.
In order to use Geofencing Methods, the following requirements apply:
  • Permissions.LOCATION permission must be granted. On iOS it must be granted with Always option — see Permissions.LOCATION for more details.
  • Geofencing task must be defined in the top-level scope, using TaskManager.defineTask.
  • On iOS, there is a limit of 20 regions that can be simultaneously monitored.
On Android, This module requires the permissions for approximate and exact device location. It also needs the foreground service permission to subscribe to location updates, while the app is in use. The ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, and FOREGROUND_SERVICE permissions are automatically added.

If you're using the iOS or Android Emulators, ensure that Location is enabled.
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import * as Location from 'expo-location';

export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
    })();
  }, []);

  let text = 'Waiting..';
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);
  }

  return (
    <View style={styles.container}>
      <Text>{text}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

import * as Location from 'expo-location';

Methods

Checks whether location services are enabled by the user.

A promise resolving to true if location services are enabled on the device, or false if not.

Asks the user to grant permissions for location. Alias for Permissions.askAsync(Permissions.LOCATION).

A promise that resolves to an object of type LocationPermissionResponse.

Checks user's permissions for accessing location. Alias for Permissions.getAsync(Permissions.LOCATION).

A promise that resolves to an object of type LocationPermissionResponse.

Gets the last known position of the device. It's considered to be faster than getCurrentPositionAsync as it doesn't request for the current location, but keep in mind the returned location may not be up-to-date.

  • options (object) — A map of options:
    • maxAge (number) — A number of miliseconds after which the last known location starts to be invalid and thus null is returned.
    • requiredAccuracy (number) — The maximum radius of uncertainty for the location, measured in meters. If the last known location's accuracy radius is bigger (less accurate) then null is returned.

Returns a promise resolving to an object of type LocationObject or null if it's not available or doesn't match given requirements such as maximum age or required accuracy.

Requests for one-time delivery of the user's current location. Depending on given accuracy option it may take some time to resolve, especially when you're inside a building.
Note: Calling it causes the location manager to obtain a location fix which may take several seconds. Consider using Location.getLastKnownPositionAsync if you expect to get a quick response and high accuracy is not required.

  • options (object) — A map of options:
    • accuracy : LocationAccuracy — Location manager accuracy. Pass one of LocationAccuracy enum values. For low-accuracy the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).

Returns a promise resolving to an object of type LocationObject.

Subscribe to location updates from the device. Please note that updates will only occur while the application is in the foreground. To get location updates while in background you'll need to use Location.startLocationUpdatesAsync.

  • options (object) — A map of options:
    • accuracy : LocationAccuracy — Location manager accuracy. Pass one of LocationAccuracy enum values. For low accuracy the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).
    • timeInterval (number) — Minimum time to wait between each update in milliseconds.
    • distanceInterval (number) — Receive updates only when the location has changed by at least this distance in meters.
    • mayShowUserSettingsDialog (boolean) — (Android only) Specifies whether to ask the user to turn on improved accuracy location mode which uses Wi-Fi, cell networks and GPS sensor. The dialog can be shown only when the location mode is set to Device only. Defaults to true.
  • callback (function) -- This function is called on each location update. It receives an object of type LocationObject as the first argument.

Returns a promise resolving to a subscription object, which has one field:
  • remove (function) -- Call this function with no arguments to remove this subscription. The callback will no longer be called for location updates.

Check status of location providers.

Returns a promise resolving to an object of type LocationProviderStatus.

Asks the user to turn on high accuracy location mode which enables network provider that uses Google Play services to improve location accuracy and location-based services.

A promise resolving as soon as the user accepts the dialog. Rejects if denied.

Gets the current heading information from the device

A promise resolving to an object of type LocationHeadingObject.

Subscribe to compass updates from the device.

  • callback (function) -- This function is called on each compass update. It receives an object of type LocationHeadingObject as the first argument.

Returns a promise resolving to a subscription object, which has one field:
  • remove (function) — Call this function with no arguments to remove this subscription. The callback will no longer be called for location updates.

Geocode an address string to latitiude-longitude location.
Note: Geocoding is resource consuming and has to be used reasonably. Creating too many requests at a time can result in an error so they have to be managed properly. It's also discouraged to use geocoding while the app is in the background and its results won't be shown to the user immediately.
On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.

  • address (string) — A string representing address, eg. "Baker Street London"
  • options (object) — A map of options:
    • useGoogleMaps (boolean) — Whether to force using Google Maps API instead of the native implementation. Used by default only on Web platform. Requires providing an API key by setGoogleApiKey.

Returns a promise resolving to an array (in most cases its size is 1) of geocoded location objects with the following fields:
  • latitude (number) — The latitude in degrees.
  • longitude (number) — The longitude in degrees.
  • altitude (number) — The altitude in meters above the WGS 84 reference ellipsoid.
  • accuracy (number) — The radius of uncertainty for the location, measured in meters.

Reverse geocode a location to postal address.
Note: Geocoding is resource consuming and has to be used reasonably. Creating too many requests at a time can result in an error so they have to be managed properly. It's also discouraged to use geocoding while the app is in the background and its results won't be shown to the user immediately.
On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.

  • location (object) — An object representing a location:
    • latitude (number) — The latitude of location to reverse geocode, in degrees.
    • longitude (number) — The longitude of location to reverse geocode, in degrees.
  • options (object) — A map of options:
    • useGoogleMaps (boolean) — Whether to force using Google Maps API instead of the native implementation. Used by default only on Web platform. Requires providing an API key by setGoogleApiKey.

Returns a promise resolving to an array (in most cases its size is 1) of address objects with following fields:
  • city (string | null) — City name of the address.
  • district (string | null) — Additional city-level information like district name.
  • street (string | null) — Street name of the address.
  • region (string | null) — The state or province associated with the address.
  • subregion (string | null) — Additional information about administrative area.
  • postalCode (string | null) — Postal code of the address.
  • country (string | null) — Localized country name of the address.
  • name (string | null) — The name of the placemark, for example, "Tower Bridge".
  • isoCountryCode (string | null) — Localized (iso) country code of the address, if available.
  • timezone (string | null) — The timezone identifier associated with the address. (iOS only)

Sets a Google API Key for using Google Maps Geocoding API which is used by default on Web platform and can be enabled through useGoogleMaps option of geocodeAsync and reverseGeocodeAsync methods. It might be useful for Android devices that do not have Google Play Services, hence no Geocoder Service.

  • apiKey (string) — Google API key obtained from Google API Console. This API key must have Geocoding API enabled, otherwise your geocoding requests will be denied.

Polyfills navigator.geolocation for interop with the core React Native and Web API approach to geolocation.

The Background Location API can notify your app about new locations while your app is backgrounded. Make sure you've followed the required steps detailed here.

Registers for receiving location updates that can also come when the app is in the background.

  • taskName (string) -- Name of the task receiving location updates.
  • options (object) -- An object of options passed to the location manager.
    • accuracy : LocationAccuracy -- Location manager accuracy. Pass one of LocationAccuracy enum values. For low-accuracy the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).
    • timeInterval (number) -- Minimum time to wait between each update in milliseconds. Default value depends on accuracy option. (Android only)
    • distanceInterval (number) -- Receive updates only when the location has changed by at least this distance in meters. Default value may depend on accuracy option.
    • deferredUpdatesInterval (number) -- Minimum time interval in miliseconds that must pass since last reported location before all later locations are reported in a batched update. Defaults to 0.
    • deferredUpdatesDistance (number) -- The distance in meters that must occur between last reported location and the current location before deferred locations are reported. Defaults to 0.
    • showsBackgroundLocationIndicator (boolean) -- A boolean indicating whether the status bar changes its appearance when location services are used in the background. Defaults to false. (Takes effect only on iOS 11.0 and later)
    • foregroundService (object) -- Use this option to put the location service into a foreground state, which will make location updates in the background as frequent as in the foreground state. As a downside, it requires a sticky notification, so the user will be aware that your app is running and consumes more resources even if backgrounded. (Available since Android 8.0)
      • notificationTitle (string) -- Title of the foreground service notification. required
      • notificationBody (string) -- Subtitle of the foreground service notification. required
      • notificationColor (string) -- Color of the foreground service notification. Accepts #RRGGBB and #AARRGGBB hex formats. optional
    • pausesUpdatesAutomatically (boolean) -- A boolean value indicating whether the location manager can pause location updates to improve battery life without sacrificing location data. When this option is set to true, the location manager pauses updates (and powers down the appropriate hardware) at times when the location data is unlikely to change. You can help the determination of when to pause location updates by assigning a value to the activityType property. Defaults to false. (iOS only)
    • activityType : LocationActivityType -- The type of user activity associated with the location updates. See Apple docs for more details. Defaults to LocationActivityType.Other. (iOS only)
Deferred updates provide a way to report locations in a batch when the app is in the background state. Location updates aren't being deferred in the foreground.

A promise resolving once the task with location updates is registered.

Background location task will be receiving following data:
import * as TaskManager from 'expo-task-manager';

TaskManager.defineTask(YOUR_TASK_NAME, ({ data: { locations }, error }) => {
  if (error) {
    // check `error.message` for more details.
    return;
  }
  console.log('Received new locations', locations);
});

Stops location updates for given task.

  • taskName (string) -- Name of the background location task to stop.

A promise resolving as soon as the task is unregistered.

  • taskName (string) -- Name of the location task to check.

A promise resolving to boolean value indicating whether the location task is started or not.

Geofencing API notifies your app when the device enters or leaves geographical regions you set up. To make it work in the background, it uses TaskManager Native API under the hood. Make sure you've followed the required steps detailed here.

Starts geofencing for given regions. When the new event comes, the task with specified name will be called with the region that the device enter to or exit from. If you want to add or remove regions from already running geofencing task, you can just call startGeofencingAsync again with the new array of regions.

  • taskName (string) -- Name of the task that will be called when the device enters or exits from specified regions.
  • regions (array) -- Array of region objects to be geofenced.
    • identifier (string) -- The identifier of the region object. Defaults to auto-generated UUID hash.
    • latitude (number) -- The latitude in degrees of region's center point. required
    • longitude (number) -- The longitude in degrees of region's center point. required
    • radius (number) -- The radius measured in meters that defines the region's outer boundary. required
    • notifyOnEnter (boolean) -- Boolean value whether to call the task if the device enters the region. Defaults to true.
    • notifyOnExit (boolean) -- Boolean value whether to call the task if the device exits the region. Defaults to true.

A promise resolving as soon as the task is registered.

Geofencing task will be receiving following data:
import { LocationGeofencingEventType } from 'expo-location';
import * as TaskManager from 'expo-task-manager';

TaskManager.defineTask(YOUR_TASK_NAME, ({ data: { eventType, region }, error }) => {
  if (error) {
    // check `error.message` for more details.
    return;
  }
  if (eventType === LocationGeofencingEventType.Enter) {
    console.log("You've entered region:", region);
  } else if (eventType === LocationGeofencingEventType.Exit) {
    console.log("You've left region:", region);
  }
});

Stops geofencing for specified task. It unregisters the background task so the app will not be receiving any updates, especially in the background.

  • taskName (string) -- Name of the task to unregister.

A promise resolving as soon as the task is unregistered.

  • taskName (string) -- Name of the geofencing task to check.

A promise resolving to boolean value indicating whether the geofencing task is started or not.

LocationPermissionResponse extends PermissionResponse type exported by unimodules-permission-interface and contains additional platform-specific fields:
  • ios (object)
    • scope (string) — The scope of granted permission. Indicates when it's possible to use location, possible values are: whenInUse, always or none.
  • android (object)
    • scope (string) — On Android it indicates the type of location provider with possible values: fine, coarse, none.

Object of type LocationObject contains following keys:
  • coords (object) — The coordinates of the position, with the following fields:
    • latitude (number) — The latitude in degrees.
    • longitude (number) — The longitude in degrees.
    • altitude (number | null) — The altitude in meters above the WGS 84 reference ellipsoid. Can be null on Web if it's not available.
    • accuracy (number | null) — The radius of uncertainty for the location, measured in meters. Can be null on Web if it's not available.
    • altitudeAccuracy (number | null) — The accuracy of the altitude value, in meters. Can be null on Web if it's not available.
    • heading (number | null) — Horizontal direction of travel of this device, measured in degrees starting at due north and continuing clockwise around the compass. Thus, north is 0 degrees, east is 90 degrees, south is 180 degrees, and so on. Can be null on Web if it's not available.
    • speed (number | null) — The instantaneous speed of the device in meters per second. Can be null on Web if it's not available.
  • timestamp (number) — The time at which this position information was obtained, in milliseconds since epoch.

Object of type LocationProviderStatus contains following keys:
  • locationServicesEnabled (boolean) -- Whether location services are enabled. See Location.hasServicesEnabledAsync for a more convenient solution to get this value.
  • gpsAvailable (boolean) -- (Android only) Whether the GPS provider is available. If true the location data will come from GPS, especially for requests with high accuracy.
  • networkAvailable (boolean) -- (Android only) Whether the network provider is available. If true the location data will come from cellular network, especially for requests with low accuracy.
  • passiveAvailable (boolean) -- (Android only) Whether the passive provider is available. If true the location data will be determined passively.

Object of type LocationRegion includes following fields:
  • identifier (string) -- The identifier of the region object passed to startGeofencingAsync or auto-generated.
  • latitude (number) -- The latitude in degress of region's center point.
  • longitude (number) -- The longitude in degress of region's center point.
  • radius (number) -- The radius measured in meters that defines the region's outer boundary.
  • state : LocationGeofencingRegionState -- One of LocationGeofencingRegionState region state. Determines whether the device is inside or outside a region.

  • magHeading (number) — Measure of magnetic north in degrees.
  • trueHeading (number) — Measure of true north in degrees (needs location permissions, will return -1 if not given).
  • accuracy (number) — Level of callibration of compass.
    • 3: high accuracy, 2: medium accuracy, 1: low accuracy, 0: none
    • Reference for iOS: 3: < 20 degrees uncertainty, 2: < 35 degrees, 1: < 50 degrees, 0: > 50 degrees

AccuracyValueDescription
Accuracy.Lowest1Accurate to the nearest three kilometers.
Accuracy.Low2Accurate to the nearest kilometer.
Accuracy.Balanced3Accurate to within one hundred meters.
Accuracy.High4Accurate to within ten meters of the desired target.
Accuracy.Highest5The best level of accuracy available.
Accuracy.BestForNavigation6The highest possible accuracy that uses additional sensor data to facilitate navigation apps.

ActivityTypeValueDescription
ActivityType.Other1Default activity type. Use it if there is no other type that matches the activity you track.
ActivityType.AutomotiveNavigation2Location updates are being used specifically during vehicular navigation to track location changes to the automobile.
ActivityType.Fitness3Use this activity type if you track fitness activities such as walking, running, cycling, and so on.
ActivityType.OtherNavigation4Activity type for movements for other types of vehicular navigation that are not automobile related.
ActivityType.Airborne5Intended for airborne activities. Available since iOS 12.0, fall backs to ActivityType.Other otherwise.

Event typeValueDescription
GeofencingEventType.Enter1Emitted when the device entered observed region.
GeofencingEventType.Exit2Occurs as soon as the device left observed region.

Region stateValueDescription
GeofencingRegionState.Inside1Indicates that the device is inside the region.
GeofencingRegionState.Outside2Inverse of inside state.

With Simulator open, go to Debug > Location and choose any option besides "None" (obviously).
iOS Simulator location

Open Android Studio, and launch your AVD in the emulator. Then, on the options bar for your device, click the icon for "More" and navigate to the "Location" tab.
Android Simulator location
If you don't receive the locations in the emulator, you may have to turn off "Improve Location Accuracy" in Settings - Location in the emulator. This will turn off Wi-Fi location and only use GPS. Then you can manipulate the location with GPS data through the emulator.