expo-location allows reading geolocation information from the device. Your app can poll for the current location or subscribe to location update events.
On iOS, there is a limit of 20regions 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{ Platform, Text, View, StyleSheet }from'react-native';%%placeholder-start%%%%placeholder-end%%import Constants from'expo-constants';import*as Location from'expo-location';exportdefaultfunctionApp(){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.requestPermissionsAsync();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;}elseif(location){
text =JSON.stringify(location);}return(<Viewstyle={styles.container}><Textstyle={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',},});
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
Background location task will be receiving following data:
locations : LocationObject[] - An array of the new locations.
import*asTaskManagerfrom'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);});
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.
import{LocationGeofencingEventType}from'expo-location';import*asTaskManagerfrom'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);}elseif(eventType ===LocationGeofencingEventType.Exit){console.log("You've left region:", region);}});
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.
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.
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.