expo-location allows reading geolocation information from the device. Your app can poll for the current location or subscribe to location update events.
If you're using the iOS or Android Emulators, ensure that Location is enabled.
importReact,{ useState, useEffect }from'react';import{Platform,Text,View,StyleSheet}from'react-native';importConstantsfrom'expo-constants';import*asLocationfrom'expo-location';exportdefaultfunctionApp(){const[location, setLocation]=useState(null);const[errorMsg, setErrorMsg]=useState(null);useEffect(()=>{(async()=>{let{ status }=awaitLocation.requestPermissionsAsync();if(status !=='granted'){setErrorMsg('Permission to access location was denied');}letlocation=awaitLocation.getCurrentPositionAsync({});setLocation(location);})();});let text ='Waiting..';if(errorMsg){
text = errorMsg;}elseif(location){
text =JSON.stringify(location);}return(<View style={styles.container}><Text style={styles.paragraph}>{text}</Text></View>);}
Note: calling it on iOS 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 : Location.Accuracy -- Location manager accuracy. Pass one of Location.Accuracy enum values. For low-accuracy the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).
maximumAge (number) -- (Android only). If specified, allow returning a previously cached position that is at most this old in milliseconds. If not specified, always gets a new location. On iOS this option is ignored and a new location is always returned.
timeout (number) -- (Android only). Specifies the duration of time in milliseconds to wait before timing out the location request.
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 : Location.Accuracy -- Location manager accuracy. Pass one of Location.Accuracy 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) -- 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. (Android only)
callback (function) --
This function is called on each location update. It is passed exactly one parameter: an object representing Location type.
Returns a promise resolving to an object with the following fields:
locationServicesEnabled (boolean) -- Whether location services are enabled. See Location.hasServicesEnabledAsync for a more convenient solution to get this value.
gpsAvailable (boolean) (android only) -- If the GPS provider is available, if yes, location data will be from GPS.
networkAvailable (boolean) (android only) -- If the network provider is available, if yes, location data will be from cellular network.
passiveAvailable (boolean) (android only) -- If the passive provider is available, if yes, location data will be determined passively.
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.
On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.
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.
On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.
Sets a Google API Key for using Geocoding API. This method can be useful for Android devices that do not have Google Play Services, hence no Geocoder Service. After setting the key using Google's API will be possible.
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 : Location.Accuracy -- Location manager accuracy. Pass one of Location.Accuracy 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 : Location.ActivityType -- The type of user activity associated with the location updates. See Apple docs for more details. Defaults to Location.ActivityType.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 : Location[] - 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*asLocationfrom'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 ===Location.GeofencingEventType.Enter){console.log("You've entered region:", region);}elseif(eventType ===Location.GeofencingEventType.Exit){console.log("You've left region:", region);}});
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) -- The altitude in meters above the WGS 84 reference ellipsoid.
accuracy (number) -- The radius of uncertainty for the location, measured in meters.
altitudeAccuracy (number) -- The accuracy of the altitude value, in meters (iOS only).
heading (number) -- 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.
speed (number) -- The instantaneous speed of the device in meters per second.
timestamp (number) -- The time at which this position information was obtained, in milliseconds since epoch.
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.