Docs-logo

Expo

Get Started
API Reference
Slash-shortcut-icon
Hamburger-icon

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
Status-success-iconStatus-success-iconStatus-success-iconStatus-success-iconStatus-success-icon

Installation

Terminal
→ 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.
  • (iOS only) "location" background mode must be specified in Info.plist file. See background tasks configuration guide.
  • 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.
Info-icon
Note: 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.
Info-icon

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

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

  useEffect(() => {
    (async () => {
      %%placeholder-start%%%%placeholder-end%%if (Platform.OS === 'android' && !Constants.isDevice) {
        setErrorMsg(
          'Oops, this will not work on Snack in an Android Emulator. Try it on your device!'
        );
        return;
      }
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      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 style={styles.paragraph}>{text}</Text>
    </View>
  );
}

%%placeholder-start%%const styles = StyleSheet.create({ ... }); %%placeholder-end%%const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
  },
  paragraph: {
    fontSize: 18,
    textAlign: 'center',
  },
});

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.

import * as Location from 'expo-location';

Arguments

NameTypeDescription
options
(optional)
PermissionHookOptions<object>-

Check or request permissions for the foreground location. This uses both requestBackgroundPermissionsAsync and getBackgroundPermissionsAsync to interact with the permissions.

Example

const [status, requestPermission] = Location.useBackgroundPermissions();

  • [null | PermissionResponse, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]

Arguments

NameTypeDescription
options
(optional)
PermissionHookOptions<object>-

Check or request permissions for the foreground location. This uses both requestForegroundPermissionsAsync and getForegroundPermissionsAsync to interact with the permissions.

Example

const [status, requestPermission] = Location.useForegroundPermissions();

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.


Arguments

NameTypeDescription
addressstringA string representing address, eg. "Baker Street London".
options
(optional)
LocationGeocodingOptions-

Geocode an address string to latitude-longitude location.

Info-icon
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.
Info-icon
On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.

A promise which fulfills with an array (in most cases its size is 1) of LocationGeocodedLocation objects.


Checks user's permissions for accessing location while the app is in the background.

A promise that fulfills with an object of type PermissionResponse.


Arguments

NameTypeDescription
optionsLocationOptions-

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.

Info-icon
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.

A promise which fulfills with an object of type LocationObject.


Checks user's permissions for accessing location while the app is in the foreground.

A promise that fulfills with an object of type PermissionResponse.


Gets the current heading information from the device. To simplify, it calls watchHeadingAsync and waits for a couple of updates, and then returns the one that is accurate enough.

A promise which fulfills with an object of type LocationHeadingObject.


Arguments

NameTypeDescription
optionsLocationLastKnownOptions-

Gets the last known position of the device or null if it's not available or doesn't match given requirements such as maximum age or required accuracy. 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.

A promise which fulfills with 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.


Info-icon
Deprecated. Deprecated. Use getForegroundPermissionsAsync or getBackgroundPermissionsAsync instead.

Checks user's permissions for accessing location.

A promise that fulfills with an object of type LocationPermissionResponse.


Check status of location providers.

A promise which fulfills with an object of type LocationProviderStatus.


Checks whether location services are enabled by the user.

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


Arguments

NameTypeDescription
taskNamestringName of the geofencing task to check.

A promise which fulfills with boolean value indicating whether the geofencing task is started or not.


Arguments

NameTypeDescription
taskNamestringName of the location task to check.

A promise which fulfills with boolean value indicating whether the location task is started or not.


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

  • void

Asks the user to grant permissions for location while the app is in the background. On Android 11 or higher: this method will open the system settings page - before that happens you should explain to the user why your application needs background location permission. For example, you can use Modal component from react-native to do that.

Info-icon
Note: Foreground permissions should be granted before asking for the background permissions

(your app can't obtain background permission without foreground permission).

A promise that fulfills with an object of type PermissionResponse.


Asks the user to grant permissions for location while the app is in the foreground.

A promise that fulfills with an object of type PermissionResponse.


Info-icon

Asks the user to grant permissions for location.

A promise that fulfills with an object of type LocationPermissionResponse.


Arguments

NameTypeDescription
locationPick<LocationGeocodedLocation, 'latitude' | 'longitude'>An object representing a location.
options
(optional)
LocationGeocodingOptions-

Reverse geocode a location to postal address.

Info-icon
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.
Info-icon
On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.

A promise which fulfills with an array (in most cases its size is 1) of LocationGeocodedAddress objects.


Arguments

NameTypeDescription
apiKeystringGoogle API key obtained from Google API Console. This API key must have Geocoding API enabled, otherwise your geocoding requests will be denied.

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.

  • void

Arguments

NameTypeDescription
taskNamestringName of the task that will be called when the device enters or exits from specified regions.
regionsLocationRegion[]Array of region objects to be geofenced.

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.

A promise resolving as soon as the task is registered.

Task parameters

Geofencing task will be receiving following data:

  • eventType - Indicates the reason for calling the task, which can be triggered by entering or exiting the region. See GeofencingEventType.
  • region - Object containing details about updated region. See LocationRegion for more details.

Example

import { GeofencingEventType } 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 === GeofencingEventType.Enter) {
    console.log("You've entered region:", region);
  } else if (eventType === GeofencingEventType.Exit) {
    console.log("You've left region:", region);
  }
});

Arguments

NameTypeDescription
taskNamestringName of the task receiving location updates.
optionsLocationTaskOptionsAn object of options passed to the location manager.

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

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

Task parameters

Background location task will be receiving following data:

  • locations - An array of the new locations.
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);
});

Arguments

NameTypeDescription
taskNamestringName of the task to unregister.

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

A promise resolving as soon as the task is unregistered.


Arguments

NameTypeDescription
taskNamestringName of the background location task to stop.

Stops geofencing for specified task.

A promise resolving as soon as the task is unregistered.


Arguments

NameTypeDescription
callbackLocationHeadingCallbackThis function is called on each compass update. It receives an object of type LocationHeadingObject as the first argument.

Subscribe to compass updates from the device.

A promise which fulfills with a LocationSubscription object.


Arguments

NameTypeDescription
optionsLocationOptions-
callbackLocationCallbackThis function is called on each location update. It receives an object of type LocationObject as the first argument.

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.

A promise which fulfills with a LocationSubscription object.

Represents watchPositionAsync callback.

Arguments

NameTypeDescription
locationLocationObject-

Type representing a result of reverseGeocodeAsync.

NameTypeDescription
citystring | nullCity name of the address.
countrystring | nullLocalized country name of the address.
districtstring | nullAdditional city-level information like district name.
isoCountryCodestring | nullLocalized (ISO) country code of the address, if available.
namestring | nullThe name of the placemark, for example, "Tower Bridge".
postalCodestring | nullPostal code of the address.
regionstring | nullThe state or province associated with the address.
streetstring | nullStreet name of the address.
streetNumberstring | nullStreet number of the address.
subregionstring | nullAdditional information about administrative area.
timezonestring | null
iOS Only

The timezone identifier associated with the address.

Type representing a result of geocodeAsync.

NameTypeDescription
accuracy
(optional)
numberThe radius of uncertainty for the location, measured in meters.
altitude
(optional)
numberThe altitude in meters above the WGS 84 reference ellipsoid.
latitudenumberThe latitude in degrees.
longitudenumberThe longitude in degrees.

An object of options for forward and reverse geocoding.

NameTypeDescription
useGoogleMaps
(optional)
booleanWhether 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.

Represents watchHeadingAsync callback.

Arguments

NameTypeDescription
locationLocationHeadingObject-

Type of the object containing heading details and provided by watchHeadingAsync callback.

NameTypeDescription
accuracynumberLevel of calibration 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
magHeadingnumberMeasure of magnetic north in degrees.
trueHeadingnumberMeasure of true north in degrees (needs location permissions, will return -1 if not given).

Type representing options object that can be passed to getLastKnownPositionAsync.

NameTypeDescription
maxAge
(optional)
numberA number of milliseconds after which the last known location starts to be invalid and thus null is returned.
requiredAccuracy
(optional)
numberThe 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.

Type representing the location object.

NameTypeDescription
coordsLocationObjectCoordsThe coordinates of the position.
timestampnumberThe time at which this position information was obtained, in milliseconds since epoch.

Type representing the location GPS related data.

NameTypeDescription
accuracynumber | nullThe radius of uncertainty for the location, measured in meters. Can be null on Web if it's not available.
altitudenumber | nullThe altitude in meters above the WGS 84 reference ellipsoid. Can be null on Web if it's not available.
altitudeAccuracynumber | nullThe accuracy of the altitude value, in meters. Can be null on Web if it's not available.
headingnumber | nullHorizontal 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.
latitudenumberThe latitude in degrees.
longitudenumberThe longitude in degrees.
speednumber | nullThe instantaneous speed of the device in meters per second. Can be null on Web if it's not available.

Type representing options argument in getCurrentPositionAsync.

NameTypeDescription
accuracy
(optional)
LocationAccuracyLocation manager accuracy. Pass one of LocationAccuracy enum values. For low-accuracies the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).
distanceInterval
(optional)
numberReceive updates only when the location has changed by at least this distance in meters. Default value may depend on accuracy option.
mayShowUserSettingsDialog
(optional)
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.

Default: true.
timeInterval
(optional)
number(Android only) Minimum time to wait between each update in milliseconds. Default value may depend on accuracy option.

Represents the object containing details about location provider.

NameTypeDescription
backgroundModeEnabledboolean-
gpsAvailable
(optional)
boolean
Android Only

Whether the GPS provider is available. If true the location data will come from GPS, especially for requests with high accuracy.
locationServicesEnabledbooleanWhether location services are enabled. See Location.hasServicesEnabledAsync for a more convenient solution to get this value.
networkAvailable
(optional)
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
(optional)
boolean
Android Only

Whether the passive provider is available. If true the location data will be determined passively.

Type representing geofencing region object.

NameTypeDescription
identifier
(optional)
stringThe identifier of the region object. Defaults to auto-generated UUID hash.
latitudenumberThe latitude in degrees of region's center point.
longitudenumberThe longitude in degrees of region's center point.
notifyOnEnter
(optional)
booleanBoolean value whether to call the task if the device enters the region.

Default: true
notifyOnExit
(optional)
booleanBoolean value whether to call the task if the device exits the region.

Default: true
radiusnumberThe radius measured in meters that defines the region's outer boundary.
state
(optional)
LocationGeofencingRegionStateOne of GeofencingRegionState region state. Determines whether the device is inside or outside a region.

Represents subscription object returned by methods watching for new locations or headings.

NameTypeDescription
remove() => voidCall this function with no arguments to remove this subscription. The callback will no longer be called for location updates.

Type representing background location task options.

LocationOptions extended by:

NameTypeDescription
activityType
(optional)
LocationActivityType
iOS Only

The type of user activity associated with the location updates.

Default: LocationActivityType.Other
Info-icon
See: See Apple docs for more details.
deferredUpdatesDistance
(optional)
numberThe distance in meters that must occur between last reported location and the current location before deferred locations are reported.

Default: 0
deferredUpdatesInterval
(optional)
numberMinimum time interval in milliseconds that must pass since last reported location before all later locations are reported in a batched update

Default: 0
deferredUpdatesTimeout
(optional)
number-
foregroundService
(optional)
LocationTaskServiceOptions-
pausesUpdatesAutomatically
(optional)
boolean
iOS Only

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.

Default: false
showsBackgroundLocationIndicator
(optional)
boolean
iOS 11+ Only

A boolean indicating whether the status bar changes its appearance when location services are used in the background.

Default: false

NameTypeDescription
notificationBodystringSubtitle of the foreground service notification.
notificationColor
(optional)
stringColor of the foreground service notification. Accepts #RRGGBB and #AARRGGBB hex formats.
notificationTitlestringTitle of the foreground service notification.

NameTypeDescription
accuracy'fine' | 'coarse' | 'none'Indicates the type of location provider.
scope'fine' | 'coarse' | 'none'-

NameTypeDescription
scope'whenInUse' | 'always' | 'none'The scope of granted permission. Indicates when it's possible to use location.

Acceptable values are: PermissionHookBehavior, Options.

Extends: UMPermissionResponse

LocationPermissionResponse extends PermissionResponse type exported by expo-modules-core and contains additional platform-specific fields.

NameTypeDescription
android
(optional)
PermissionDetailsLocationAndroid-
ios
(optional)
PermissionDetailsLocationIOS-

Enum with available location accuracies.

  • Lowest - Accurate to the nearest three kilometers.

    Accuracy.Lowest1

  • Low - Accurate to the nearest kilometer.

    Accuracy.Low2

  • Balanced - Accurate to within one hundred meters.

    Accuracy.Balanced3

  • High - Accurate to within ten meters of the desired target.

    Accuracy.High4

  • Highest - The best level of accuracy available.

    Accuracy.Highest5

  • BestForNavigation - The highest possible accuracy that uses additional sensor data to facilitate navigation apps.

    Accuracy.BestForNavigation6

Enum with available activity types of background location tracking.

  • Other - Default activity type. Use it if there is no other type that matches the activity you track.

    ActivityType.Other1

  • AutomotiveNavigation - Location updates are being used specifically during vehicular navigation to track location changes to the automobile.

    ActivityType.AutomotiveNavigation2

  • Fitness - Use this activity type if you track fitness activities such as walking, running, cycling, and so on.

    ActivityType.Fitness3

  • OtherNavigation - Activity type for movements for other types of vehicular navigation that are not automobile related.

    ActivityType.OtherNavigation4

  • Airborne -
    iOS 12+ Only
    Intended for airborne activities. Fall backs to ActivityType.Other if unsupported.

    ActivityType.Airborne5

A type of the event that geofencing task can receive.

  • Enter - Emitted when the device entered observed region.

    GeofencingEventType.Enter1

  • Exit - Occurs as soon as the device left observed region

    GeofencingEventType.Exit2

State of the geofencing region that you receive through the geofencing task.

  • Unknown - Indicates that the device position related to the region is unknown.

    GeofencingRegionState.Unknown0

  • Inside - Indicates that the device is inside the region.

    GeofencingRegionState.Inside1

  • Outside - Inverse of inside state.

    GeofencingRegionState.Outside2

  • DENIED

    PermissionStatus.DENIED"denied"

  • GRANTED

    PermissionStatus.GRANTED"granted"

  • UNDETERMINED

    PermissionStatus.UNDETERMINED"undetermined"