This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 57).
Expo 位置
一个用于访问地理位置信息、轮询当前位置或订阅设备位置更新事件的库。
expo-location 允许从设备读取地理位置信息。你的应用可以轮询当前位置信息,或者订阅位置更新事件。
安装
If you are installing this in an existing React Native app, make sure to install expo in your project.
在应用配置中进行配置
如果你的项目使用 config plugins(Continuous Native Generation (CNG)),你可以使用 expo-location 内置的 config plugin 来进行配置。该插件允许你配置一些无法在运行时设置、且需要构建新的应用二进制文件才会生效的属性。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
Configurable properties
Are you using this library in an existing React Native app?
如果你没有使用 Continuous Native Generation (CNG),或者你是手动使用原生 ios 项目,那么你需要将 NSLocationAlwaysAndWhenInUseUsageDescription、NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription 键添加到项目的 ios/[app]/Info.plist 中:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>允许 $(PRODUCT_NAME) 使用你的位置信息</string> <key>NSLocationAlwaysUsageDescription</key> <string>允许 $(PRODUCT_NAME) 使用你的位置信息</string> <key>NSLocationWhenInUseUsageDescription</key> <string>允许 $(PRODUCT_NAME) 使用你的位置信息</string>
后台位置
后台位置允许你的应用在后台运行时接收位置更新,并且包括通过地理围栏进行的位置更新和区域监测。此功能受平台 API 限制和系统约束影响:
- 当用户终止应用时,后台位置会停止。
- 当用户重新启动应用时,后台位置会恢复。
- Android由于平台限制,终止的应用在发生位置或地理围栏事件时不会自动重启。
- iOS当新的地理围栏事件发生时,系统会重启已终止的应用。
信息 在 Android 上,将应用从最近任务列表中移除的结果因设备厂商而异。例如,有些实现会将其视为杀死应用。更多关于这些差异的信息请见:https://dontkillmyapp.com。
后台位置配置 iOS
要在 iOS 上运行后台位置,你需要在应用的 Info.plist 文件中的 UIBackgroundModes 数组里添加 location 值。
如果你使用的是 CNG,所需的 UIBackgroundModes 配置会在 prebuild 过程中自动应用。
在 iOS 上手动配置 UIBackgroundModes
如果你没有使用 Continuous Native Generation (CNG),或者你正在使用原生 iOS 项目,那么你需要将以下内容添加到 Expo.plist 文件中:
后台位置方法
要使用后台位置方法,需要满足以下要求:
- 必须授予位置权限。
- 必须在顶层作用域中使用
TaskManager.defineTask定义后台位置任务。 - iOS必须在 Info.plist 文件中指定
"location"后台模式。请参阅后台位置配置。 - iOS由于 Expo Go 应用不支持后台位置,因此你必须使用开发构建来使用后台位置。
地理围栏方法
要使用地理围栏方法,需要满足以下要求:
- 必须授予位置权限。
- 必须在顶层作用域中使用
TaskManager.defineTask定义地理围栏任务。
使用地理围栏时,适用以下平台差异:
后台权限
要在后台使用位置跟踪或地理围栏,你必须请求相应的权限:
- 在 Android 上,你必须同时请求前台和后台权限。
- 在 iOS 上,必须使用
requestBackgroundPermissionsAsync以Always选项授予权限。
Expo 和 iOS 权限
iOS 权限分为 When In Use 和 Always 两类,分别对应通过以下方法请求的 Expo 前台和后台位置权限:
requestForegroundPermissionsAsync对应When In UserequestBackgroundPermissionsAsync对应Always
注意: 请求
When In Use授权时,用户可以在系统权限对话框中选择Allow Once,授予临时访问权限。此授权仅对当前应用会话有效,并会在应用关闭时自动撤销。
区分 “Allow Once” 与 “Allow While Using the App”
遗憾的是,iOS 无法提供一种方式来检测用户选择的是 Allow Once 还是 Allow While Using the App。这两种响应都会得到 When In Use 授权。
如果用户选择了 Allow Once,而你随后在同一会话中调用 requestBackgroundPermissionsAsync,系统不会再显示另一个提示。相反,请求会静默失败,返回的后台权限状态将是被拒绝。
处理 “Allow Once” 场景
如果你怀疑用户选择了 Allow Once 且需要请求后台权限,他们必须在设置应用中手动启用后台位置。你可以使用 Linking 在应用中打开设置应用:
import { Linking } from 'react-native'; function openSettings() { Linking.openURL('app-settings:'); }
逐步请求权限
可以先请求前台位置访问权限,然后再在之后请求后台位置访问权限。这样可以仅在必要时请求权限,从而改善用户体验。
直接请求后台权限
如果你在未先请求前台权限的情况下调用 requestBackgroundPermissionsAsync,iOS 会将其视为同时请求 When In Use 和 Always 授权。系统随后会提示用户授予 When In Use 访问权限,而当系统判断需要 Always 授权时,会显示 Always 授权提示。
请记住,用户也可以选择仅授予你的应用 When In Use 授权。你必须始终准备好在 When In Use 权限下运行。
延迟位置
在使用后台位置时,你可以配置位置管理器以延迟更新。这通过降低更新频率有助于节省电量。你可以将更新设置为仅在设备移动了某个距离后,或在经过指定时间间隔后触发。
延迟更新通过 LocationTaskOptions 进行配置,使用 deferredUpdatesDistance、deferredUpdatesInterval 和 deferredTimeout 属性。
延迟位置仅在应用处于后台时适用。
用法
如果你正在使用 Android 模拟器或 iOS 模拟器,请确保已启用位置。
启用模拟器位置
Android 模拟器
打开 Android Studio,并启动 Android 模拟器。在其中,进入 设置 > 位置,并启用 使用位置。
如果你没有在模拟器中接收到位置,你可能需要关闭提高位置精度设置。这将关闭 Wi-Fi 定位并且仅使用 GPS。然后你可以通过模拟器使用 GPS 数据来操控位置。
对于 Android 12 及更高版本,进入设置 > 位置 > 位置服务 > Google 位置精度,并关闭提高位置精度。对于 Android 11 及更低版本,进入设置 > 位置 > 高级 > Google 位置精度,并关闭Google 位置精度。
iOS 模拟器
打开 Device Hub 后,进入设备 > 位置,并选择 无 以外的任一选项。
API
import * as Location from 'expo-location';
Hooks
Check or request permissions for the background location.
This uses both requestBackgroundPermissionsAsync and getBackgroundPermissionsAsync to
interact with the permissions.
[LocationPermissionResponse | null, RequestPermissionMethod<LocationPermissionResponse>, GetPermissionMethod<LocationPermissionResponse>]Example
const [status, requestPermission] = Location.useBackgroundPermissions();
Check or request permissions for the foreground location.
This uses both requestForegroundPermissionsAsync and getForegroundPermissionsAsync to interact with the permissions.
[LocationPermissionResponse | null, RequestPermissionMethod<LocationPermissionResponse>, GetPermissionMethod<LocationPermissionResponse>]Example
const [status, requestPermission] = Location.useForegroundPermissions();
Checks or requests permissions for motion activity detection.
This uses both requestMotionActivityPermissionsAsync and getMotionActivityPermissionsAsync
to interact with the permissions.
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = Location.useMotionActivityPermissions();
Methods
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.
Promise<void>A promise resolving as soon as the user accepts the dialog. Rejects if denied.
Geocode an address string to latitude-longitude location.
On Android, you must request location permissions with requestForegroundPermissionsAsync
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. 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.
Promise<LocationGeocodedLocation[]>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.
Promise<LocationPermissionResponse>A promise that fulfills with an object of type LocationPermissionResponse.
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
getLastKnownPositionAsyncif you expect to get a quick response and high accuracy is not required.
Promise<LocationObject>A promise which fulfills with an object of type LocationObject.
Checks user's permissions for accessing location while the app is in the foreground.
Promise<LocationPermissionResponse>A promise that fulfills with an object of type LocationPermissionResponse.
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.
Promise<LocationHeadingObject>A promise which fulfills with an object of type LocationHeadingObject.
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.
Promise<LocationObject | null>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.
Fetches the current motion activity status of the device by subscribing to the first available
activity update and immediately unsubscribing afterwards.
The returned promise fulfills with the same object shape as the watchMotionActivityAsync
callback.
The method uses the Google Play Services activity
recognition (Android) or platform's motion coprocessor (iOS) and does not require location permissions.
On Android 10+, the ACTIVITY_RECOGNITION runtime permission must be granted beforehand.
On iOS, the system will prompt the user for Motion and Fitness access the first time this method is called.
Promise<MotionActivityObject>a promise which fulfills with a MotionActivityObject.
Checks user's permissions for accessing motion activity data.
Promise<PermissionResponse>A promise that fulfills with an object of type PermissionResponse.
Check status of location providers.
Promise<LocationProviderStatus>A promise which fulfills with an object of type LocationProviderStatus.
Checks whether location services are enabled by the user.
Promise<boolean>A promise which fulfills to true if location services are enabled on the device,
or false if not.
Promise<boolean>A promise which fulfills with boolean value indicating whether the geofencing task is started or not.
Promise<boolean>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.
voidPromise<boolean>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.
Note: Foreground permissions should be granted before asking for the background permissions (your app can't obtain background permission without foreground permission).
Promise<LocationPermissionResponse>A promise that fulfills with an object of type LocationPermissionResponse.
Asks the user to grant permissions for location while the app is in the foreground.
Promise<LocationPermissionResponse>A promise that fulfills with an object of type LocationPermissionResponse.
Asks the user to grant permissions for motion activity detection.
On Android 10+, this requests the ACTIVITY_RECOGNITION runtime permission.
On iOS, this triggers the system prompt for Motion and Fitness access the first time it is called.
Promise<PermissionResponse>a promise that fulfills with an object of type PermissionResponse.
Reverse geocode a location to postal address.
On Android, you must request location permissions with requestForegroundPermissionsAsync
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. 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.
Promise<LocationGeocodedAddress[]>A promise which fulfills with an array (in most cases its size is 1) of LocationGeocodedAddress objects.
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.
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. SeeGeofencingEventType.region- Object containing details about updated region. SeeLocationRegionfor more details.
Promise<void>A promise resolving as soon as the task is registered.
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); } });
Registers for receiving location updates that can also come when the app is in the background.
Task parameters
Background location task will be receiving following data:
locations- An array of the new locations.
Promise<void>A promise resolving once the task with location updates is registered.
Example
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 geofencing for specified task. It unregisters the background task so the app will not be receiving any updates, especially in the background.
Promise<void>A promise resolving as soon as the task is unregistered.
Stops location updates for specified task.
Promise<void>A promise resolving as soon as the task is unregistered.
Subscribe to compass updates from the device.
Promise<LocationSubscription>A promise which fulfills with a LocationSubscription object.
Subscribes to motion activity updates from the device. The callback fires whenever the platform's motion coprocessor detects a change in the user's activity. Only foreground use is supported - updates pause when the app is backgrounded and resume when it returns to the foreground.
Promise<LocationSubscription>a promise which fulfills with a LocationSubscription object.
Subscribe to location updates from the device. Updates will only occur while the application is in
the foreground. To get location updates while in background you'll need to use
startLocationUpdatesAsync.
Promise<LocationSubscription>A promise which fulfills with a LocationSubscription object.
Types
Type of the object containing heading details and provided by watchHeadingAsync callback.
Type representing options object that can be passed to getLastKnownPositionAsync.
LocationPermissionResponse extends PermissionResponse
type exported by expo-modules-core and contains additional platform-specific fields.
Type: PermissionResponse extended by:
Represents the object containing details about location provider.
Represents subscription object returned by methods watching for new locations or headings.
Represents the watchMotionActivityAsync callback.
any
Type returned by getMotionActivityAsync and the watchMotionActivityAsync callback.
Contains one entry per MotionActivityType so callers can inspect each activity
independently without searching through an array.
Example
const { activities } = await Location.getMotionActivityAsync(); if (activities.automotive.detected) { console.log('driving, confidence:', activities.automotive.confidence); }
Detection state for a single activity type.
When detected is false, confidence is always Low.
Literal type: union
Permission expiration time. Currently, all permissions are granted permanently.
Acceptable values are: 'never' | number
Literal type: union
Acceptable values are: PermissionHookBehavior | Options
Enums
Enum with available location accuracies.
Enum with available activity types of background location tracking.
ActivityType.Other = 1Default activity type. Use it if there is no other type that matches the activity you track.
ActivityType.AutomotiveNavigation = 2Location updates are being used specifically during vehicular navigation to track location changes to the automobile.
ActivityType.Fitness = 3Use this activity type if you track fitness activities such as walking, running, cycling, and so on.
ActivityType.OtherNavigation = 4Activity type for movements for other types of vehicular navigation that are not automobile related.
A type of the event that geofencing task can receive.
State of the geofencing region that you receive through the geofencing task.
GeofencingRegionState.Unknown = 0Indicates that the device position related to the region is unknown.
Confidence level for motion activity detection. On Android, the raw DetectedActivity confidence (0-
100) is bucketed into these three levels. On iOS, maps directly to CMMotionActivityConfidence.
The type of physical activity the user is currently performing.
On Android it maps to DetectedActivity constants from Google Play Services.
On iOS this maps to the boolean properties of CMMotionActivity (the highest-priority
truthy property wins).
MotionActivityType.Automotive = "automotive"The device is in a motorized vehicle (car, bus, train, and so on).
权限
Android
警告 Android 版 Expo Go 中不提供前台和后台服务。作为替代,我们建议使用开发构建以避免限制。
当你安装 expo-location 模块时,它会自动添加以下权限:
ACCESS_COARSE_LOCATION:用于近似设备位置ACCESS_FINE_LOCATION:用于精确设备位置
以下权限是可选的:
FOREGROUND_SERVICE和FOREGROUND_SERVICE_LOCATION:用于在应用打开但处于后台时访问位置。FOREGROUND_SERVICE_LOCATION仅从 Android 14 开始需要。当你在新构建中启用此项时,你需要提交应用进行审核并申请使用前台服务权限。ACCESS_BACKGROUND_LOCATION:用于在应用处于后台或关闭时访问位置。当你在新构建中启用此项时,你需要提交应用进行审核并申请使用后台位置权限。
排除权限
注意:在你的应用中从某个模块排除一个必需权限可能会破坏该权限对应的功能。请始终确保包含模块所依赖的所有权限。
当你的 Expo 项目无法从包含某些特定权限中获益时,你可以省略这些权限。例如,如果你的应用不需要访问精确位置,你可以排除 ACCESS_FINE_LOCATION 权限。
另一个示例可以使用可用的位置精度来说明。Android 将近似位置精度估计定义为约 3 平方公里,将精确位置精度估计定义为约 50 米。例如,如果位置精度值为 Low,你可以排除 ACCESS_FINE_LOCATION 权限。要了解有关位置精度级别的更多信息,请参阅Android 文档。
要详细了解如何排除权限,请参阅排除 Android 权限。
iOS
此库使用以下用途说明键:
自 iOS 11 起,NSLocationAlwaysUsageDescription 已被弃用,推荐使用 NSLocationAlwaysAndWhenInUseUsageDescription。