Expo 位置
一个提供读取地理位置信息、轮询当前位置或订阅设备位置更新事件访问能力的库。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
expo-location 允许从设备读取地理位置信息。你的应用可以轮询当前位置信息,或订阅位置更新事件。
安装
- npx expo install expo-locationIf you are installing this in an existing React Native app, make sure to install expo in your project.
在 app 配置中进行配置
如果你在项目中使用 config plugins(Continuous Native Generation (CNG)),可以使用 expo-location 内置的 config plugin 来进行配置。该插件允许你配置一些无法在运行时设置、且需要构建新的应用二进制文件后才会生效的属性。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
{ "expo": { "plugins": [ [ "expo-location", { "locationAlwaysAndWhenInUsePermission": "允许 $(PRODUCT_NAME) 使用你的位置。" } ] ] } }
Configurable properties
| Name | Default | Description |
|---|---|---|
locationAlwaysAndWhenInUsePermission | "允许 $(PRODUCT_NAME) 使用你的位置" | Only for: iOS 用于设置 |
locationAlwaysPermission | "允许 $(PRODUCT_NAME) 使用你的位置" | Deprecated • iOS 用于设置 |
locationWhenInUsePermission | "允许 $(PRODUCT_NAME) 使用你的位置" | Only for: iOS 用于设置 |
isIosBackgroundLocationEnabled | false | Only for: iOS 一个布尔值,用于在 Info.plist 的 |
isAndroidBackgroundLocationEnabled | false | Only for: Android 一个布尔值,用于启用 |
isAndroidForegroundServiceEnabled | - | Only for: Android 一个布尔值,用于启用 |
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 文件中:
<key>UIBackgroundModes</key> <array> <string>location</string> </array>
后台位置方法
要使用后台位置方法,需要满足以下要求:
- 必须授予位置权限。
- 必须在顶层作用域中使用
TaskManager.defineTask定义后台位置任务。 - iOSInfo.plist 文件中必须指定
"location"后台模式。请参见后台位置 配置。 - iOS你必须使用 development build 才能使用后台位置,因为 Expo Go 应用不支持它。
地理围栏方法
要使用地理围栏方法,需要满足以下要求:
- 必须授予位置权限。
- 必须在顶层作用域中使用
TaskManager.defineTask定义地理围栏任务。
使用地理围栏时,适用以下平台差异:
- Android每个应用最多允许 100 个 活跃 的地理围栏。
- iOSExpo Location 会在应用启动时报告已注册 地理围栏的初始状态。
- iOS可同时监测的
regions数量上限为 20 个。
后台权限
要在后台使用位置追踪或地理围栏,你必须请求相应的权限:
- 在 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,系统不会再显示另一个提示。相反,这次请求会静默失败,返回的后台权限状态将为denied。
处理 “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 模拟器,请确保已启用位置。
import { useState, useEffect } from 'react'; import { Platform, Text, View, StyleSheet } from 'react-native'; %%placeholder-start%%%%placeholder-end%%import * as Device from 'expo-device'; import * as Location from 'expo-location'; export default function App() { const [location, setLocation] = useState<Location.LocationObject | null>(null); const [errorMsg, setErrorMsg] = useState<string | null>(null); useEffect(() => { async function getCurrentLocation() { %%placeholder-start%%%%placeholder-end%%if (Platform.OS === 'android' && !Device.isDevice) { setErrorMsg( '糟糕,这在 Android 模拟器上的 Snack 中无法运行。请在你的设备上尝试!' ); return; } let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { setErrorMsg('访问位置的权限被拒绝'); return; } let location = await Location.getCurrentPositionAsync({}); setLocation(location); } getCurrentLocation(); }, []); let text = '等待中...'; if (errorMsg) { text = errorMsg; } else if (location) { text = JSON.stringify(location); } return ( <View style={styles.container}> <Text style={styles.paragraph}>{text}</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 20, }, paragraph: { fontSize: 18, textAlign: 'center', }, });
启用模拟器位置
Android 模拟器
打开 Android Studio,并启动 Android 模拟器。在其中,进入 Settings > Location 并启用 Use location。
如果你在模拟器中没有收到位置,你可能需要关闭 Improve Location Accuracy 设置。这将关闭 Wi-Fi 定位并且只使用 GPS。然后你可以通过模拟器使用 GPS 数据来操控位置。
对于 Android 12 及更高版本,进入 Settings > Location > Location Services > Google Location Accuracy,并关闭 Improve Location Accuracy。对于 Android 11 及更低版本,进入 Settings > Location > Advanced > Google Location Accuracy,并关闭 Google Location Accuracy。
iOS 模拟器
打开模拟器后,进入 Features > Location,并选择除 None 之外的任意选项。
API
import * as Location from 'expo-location';
Hooks
| Parameter | Type |
|---|---|
| options(optional) | PermissionHookOptions<object> |
Check or request permissions for the background location.
This uses both requestBackgroundPermissionsAsync and getBackgroundPermissionsAsync to
interact with the permissions.
[null | PermissionResponse, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = Location.useBackgroundPermissions();
| Parameter | Type |
|---|---|
| options(optional) | PermissionHookOptions<object> |
Check or request permissions for the foreground location.
This uses both requestForegroundPermissionsAsync and getForegroundPermissionsAsync to interact with the permissions.
[null | LocationPermissionResponse, RequestPermissionMethod<LocationPermissionResponse>, GetPermissionMethod<LocationPermissionResponse>]Example
const [status, requestPermission] = Location.useForegroundPermissions();
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.
| Parameter | Type | Description |
|---|---|---|
| address | string | A string representing address, eg. |
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<PermissionResponse>A promise that fulfills with an object of type PermissionResponse.
| Parameter | Type |
|---|---|
| options(optional) | LocationOptions |
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.
| Parameter | Type |
|---|---|
| options(optional) | LocationLastKnownOptions |
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.
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.
| Parameter | Type | Description |
|---|---|---|
| taskName | string | Name of the geofencing task to check. |
Promise<boolean>A promise which fulfills with boolean value indicating whether the geofencing task is started or not.
| Parameter | Type | Description |
|---|---|---|
| taskName | string | Name of the location task to check. |
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<PermissionResponse>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.
Promise<LocationPermissionResponse>A promise that fulfills with an object of type LocationPermissionResponse.
| Parameter | Type | Description |
|---|---|---|
| location | Pick<LocationGeocodedLocation, 'latitude' | 'longitude'> | An object representing a location. |
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.
| Parameter | Type | Description |
|---|---|---|
| taskName | string | Name of the task that will be called when the device enters or exits from specified regions. |
| regions(optional) | LocationRegion[] | Array of region objects to be geofenced. Default: [] |
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); } });
| Parameter | Type | Description |
|---|---|---|
| taskName | string | Name of the task receiving location updates. |
| options(optional) | LocationTaskOptions | An object of options passed to the location manager. |
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); });
| Parameter | Type | Description |
|---|---|---|
| taskName | string | Name 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.
Promise<void>A promise resolving as soon as the task is unregistered.
| Parameter | Type | Description |
|---|---|---|
| taskName | string | Name of the background location task to stop. |
Stops location updates for specified task.
Promise<void>A promise resolving as soon as the task is unregistered.
| Parameter | Type | Description |
|---|---|---|
| callback | LocationHeadingCallback | This function is called on each compass update. It receives an object of type LocationHeadingObject as the first argument. |
| errorHandler(optional) | LocationErrorCallback | This function is called when an error occurs. It receives a string with the error message as the first argument. |
Subscribe to compass updates from the device.
Promise<LocationSubscription>A promise which fulfills with a LocationSubscription object.
| Parameter | Type | Description |
|---|---|---|
| options | LocationOptions | - |
| callback | LocationCallback | This function is called on each location update. It receives an object of type
|
| errorHandler(optional) | LocationErrorCallback | This function is called when an error occurs. It receives a string with the error message as the first argument. |
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
Error callback for location methods.
| Parameter | Type |
|---|---|
| reason | string |
void
Type representing a result of reverseGeocodeAsync.
| Property | Type | Description |
|---|---|---|
| city | string | null | City name of the address. |
| country | string | null | Localized country name of the address. |
| district | string | null | Additional city-level information like district name. |
| formattedAddress | string | null | Only for: Android Composed string of the address components, for example, "111 8th Avenue, New York, NY". |
| isoCountryCode | string | null | Localized (ISO) country code of the address, if available. |
| name | string | null | The name of the placemark, for example, "Tower Bridge". |
| postalCode | string | null | Postal code of the address. |
| region | string | null | The state or province associated with the address. |
| street | string | null | Street name of the address. |
| streetNumber | string | null | Street number of the address. |
| subregion | string | null | Additional information about administrative area. |
| timezone | string | null | Only for: iOS The timezone identifier associated with the address. |
Type representing a result of geocodeAsync.
| Property | Type | Description |
|---|---|---|
| accuracy(optional) | number | The radius of uncertainty for the location, measured in meters. |
| altitude(optional) | number | The altitude in meters above the WGS 84 reference ellipsoid. |
| latitude | number | The latitude in degrees. |
| longitude | number | The longitude in degrees. |
Type of the object containing heading details and provided by watchHeadingAsync callback.
| Property | Type | Description |
|---|---|---|
| accuracy | number | Level of calibration of compass:
Reference for iOS:
|
| magHeading | number | Measure of magnetic north in degrees. |
| trueHeading | number | Measure of true north in degrees (needs location permissions, will return |
Type representing options object that can be passed to getLastKnownPositionAsync.
| Property | Type | Description |
|---|---|---|
| maxAge(optional) | number | A number of milliseconds after which the last known location starts to be invalid and thus
|
| requiredAccuracy(optional) | 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 |
Type representing the location object.
| Property | Type | Description |
|---|---|---|
| coords | LocationObjectCoords | The coordinates of the position. |
| mocked(optional) | boolean | Only for: Android Whether the location coordinates is mocked or not. |
| timestamp | number | The time at which this position information was obtained, in milliseconds since epoch. |
Type representing the location GPS related data.
| Property | Type | Description |
|---|---|---|
| accuracy | number | null | The radius of uncertainty for the location, measured in meters. Can be |
| altitude | number | null | The altitude in meters above the WGS 84 reference ellipsoid. Can be |
| altitudeAccuracy | number | null | The accuracy of the altitude value, in meters. Can be |
| 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 |
| latitude | number | The latitude in degrees. |
| longitude | number | The longitude in degrees. |
| speed | number | null | The instantaneous speed of the device in meters per second. Can be |
Type representing options argument in getCurrentPositionAsync.
| Property | Type | Description |
|---|---|---|
| accuracy(optional) | Accuracy | Location manager accuracy. Pass one of Default: LocationAccuracy.Balanced |
| distanceInterval(optional) | number | Receive updates only when the location has changed by at least this distance in meters.
Default value may depend on |
| mayShowUserSettingsDialog(optional) | boolean | Only for: Android 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 | Only for: Android Minimum time to wait between each update in milliseconds.
Default value may depend on |
LocationPermissionResponse extends PermissionResponse
type exported by expo-modules-core and contains additional platform-specific fields.
Type: PermissionResponse extended by:
| Property | Type | Description |
|---|---|---|
| android(optional) | PermissionDetailsLocationAndroid | - |
| ios(optional) | PermissionDetailsLocationIOS | - |
Represents the object containing details about location provider.
| Property | Type | Description |
|---|---|---|
| backgroundModeEnabled | boolean | - |
| gpsAvailable(optional) | boolean | Only for: Android Whether the GPS provider is available. If |
| locationServicesEnabled | boolean | Whether location services are enabled. See Location.hasServicesEnabledAsync for a more convenient solution to get this value. |
| networkAvailable(optional) | boolean | Only for: Android Whether the network provider is available. If |
| passiveAvailable(optional) | boolean | Only for: Android Whether the passive provider is available. If |
Type representing geofencing region object.
| Property | Type | Description |
|---|---|---|
| identifier(optional) | string | The identifier of the region object. Defaults to auto-generated UUID hash. |
| latitude | number | The latitude in degrees of region's center point. |
| longitude | number | The longitude in degrees of region's center point. |
| notifyOnEnter(optional) | boolean | Boolean value whether to call the task if the device enters the region. Default: true |
| notifyOnExit(optional) | boolean | Boolean value whether to call the task if the device exits the region. Default: true |
| radius | number | The radius measured in meters that defines the region's outer boundary. |
| state(optional) | GeofencingRegionState | One 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.
| Property | Type | Description |
|---|---|---|
| remove | () => void | Call 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.
Type: LocationOptions extended by:
| Property | Type | Description |
|---|---|---|
| activityType(optional) | ActivityType | Only for: iOS The type of user activity associated with the location updates. Default: ActivityType.Other
|
| deferredUpdatesDistance(optional) | number | The distance in meters that must occur between last reported location and the current location before deferred locations are reported. Default: 0 |
| deferredUpdatesInterval(optional) | number | Minimum 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 | Only for: iOS 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
Default: false |
| showsBackgroundLocationIndicator(optional) | boolean | Only for: iOS A boolean indicating whether the status bar changes its appearance when location services are used in the background. Default: false |
| Property | Type | Description |
|---|---|---|
| killServiceOnDestroy(optional) | boolean | Boolean value whether to destroy the foreground service if the app is killed. |
| notificationBody | string | Subtitle of the foreground service notification. |
| notificationColor(optional) | string | Color of the foreground service notification. Accepts |
| notificationTitle | string | Title of the foreground service notification. |
| Property | Type | Description |
|---|---|---|
| accuracy | 'fine' | 'coarse' | 'none' | Indicates the type of location provider. |
| Property | Type | Description |
|---|---|---|
| scope | 'whenInUse' | 'always' | 'none' | The scope of granted permission. Indicates when it's possible to use location. |
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
An object obtained by permissions get and request functions.
| Property | Type | Description |
|---|---|---|
| canAskAgain | boolean | Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission. |
| expires | PermissionExpiration | Determines time when the permission expires. |
| granted | boolean | A convenience boolean that indicates if the permission is granted. |
| status | PermissionStatus | Determines the status of the permission. |
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.
权限
Android
警告 Expo Go for Android 中不可用前台和后台服务。因此,我们建议使用开发构建以避免限制。
当你安装 expo-location 模块时,它会自动添加以下权限:
ACCESS_COARSE_LOCATION:用于大致设备位置ACCESS_FINE_LOCATION:用于精确设备位置
以下权限是可选的:
FOREGROUND_SERVICE和FOREGROUND_SERVICE_LOCATION:用于在应用打开但处于后台时访问位置。FOREGROUND_SERVICE_LOCATION仅从 Android 14 开始需要。当你在新构建中启用此项时,你需要提交应用进行审核并申请使用前台服务权限。ACCESS_BACKGROUND_LOCATION:用于在应用处于后台或关闭时访问位置。当你在新构建中启用此项时,你需要提交应用进行审核并申请使用后台位置权限。
| Android Permission | Description |
|---|---|
Allows an app to access approximate location.
| |
Allows an app to access precise location.
| |
Allows a regular application to use Service.startForeground.
| |
Allows a regular application to use Service.startForeground with the type "location".
| |
Allows an app to access location in the background.
|
排除权限
注意:从应用中的模块排除一个必需权限可能会破坏该权限对应的功能。请始终确保包含模块所依赖的所有权限。
当你的 Expo 项目不需要包含某个特定权限时,你可以省略它。例如,如果你的应用不需要访问精确位置,你可以排除 ACCESS_FINE_LOCATION 权限。
还可以使用可用的位置精度来说明另一个例子。Android 将大致位置精度估计为约 3 平方公里,将精确位置精度估计为约 50 米。例如,如果位置精度值为Low,你可以排除 ACCESS_FINE_LOCATION 权限。要了解更多关于位置精度级别的信息,请参阅Android 文档。
要了解更多如何排除权限,请参阅排除 Android 权限。
iOS
此库使用以下用途说明键:
| Info.plist Key | Description |
|---|---|
| A message that tells the user why the app is requesting access to the user’s location information at all times. | |
| A message that tells the user why the app is requesting access to the user's location at all times.DeprecatedFor apps deployed to targets in iOS 11 and later, use NSLocationAlwaysAndWhenInUseUsageDescription instead. | |
| A message that tells the user why the app is requesting access to the user’s location information while the app is running in the foreground. |
从 iOS 11 开始,NSLocationAlwaysUsageDescription 已弃用,建议改用 NSLocationAlwaysAndWhenInUseUsageDescription。