Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo 位置 iconExpo 位置

一个提供访问地理位置信息、轮询当前位置或订阅设备位置更新事件的库。

Android
iOS
Web
Included in Expo Go
Recommended version:
~57.0.0

expo-location 允许从设备读取地理位置信息。你的应用可以轮询当前位置,或订阅位置更新事件。

安装

Terminal
npx expo install expo-location

If you are installing this in an existing React Native app, make sure to install expo in your project.

应用配置中的配置

如果你在项目中使用配置插件(Continuous Native Generation (CNG)),你可以使用 expo-location 内置的 config plugin 进行配置。该插件允许你配置一些无法在运行时设置、且需要重新构建新的应用二进制文件后才会生效的属性。如果你的应用使用 CNG,那么你需要手动配置该库。

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-location", { "locationAlwaysAndWhenInUsePermission": "允许 $(PRODUCT_NAME) 使用你的位置。" } ] ] } }

Configurable properties

NameDefaultDescription
locationAlwaysAndWhenInUsePermission"允许 $(PRODUCT_NAME) 使用你的位置"
Only for:
iOS

用于设置 NSLocationAlwaysAndWhenInUseUsageDescription 权限提示信息的字符串。

locationAlwaysPermission"允许 $(PRODUCT_NAME) 使用你的位置"
Deprecated
 • 
Only for:
iOS

用于设置 NSLocationAlwaysUsageDescription 权限提示信息的字符串。

locationWhenInUsePermission"允许 $(PRODUCT_NAME) 使用你的位置"
Only for:
iOS

用于设置 NSLocationWhenInUseUsageDescription 权限提示信息的字符串。

isIosBackgroundLocationEnabledfalse
Only for:
iOS

用于在 Info.plist 中的 UIBackgroundModes 里启用 location 的布尔值。

isAndroidBackgroundLocationEnabledfalse
Only for:
Android

用于启用 ACCESS_BACKGROUND_LOCATION 权限的布尔值。

isAndroidForegroundServiceEnabled-
Only for:
Android

用于启用 FOREGROUND_SERVICE 权限和 FOREGROUND_SERVICE_LOCATION 的布尔值。如果 isAndroidBackgroundLocationEnabledtrue,默认值为 true,否则为 false

androidForegroundServiceIcon-
Only for:
Android

作为 startLocationUpdatesAsync 启动的前台服务图标使用的图片本地路径。应为 96x96、全白、带透明通道的 png 文件。如果未设置,则会回退到 notification_icon drawable(如果已通过 expo-notifications 配置插件配置),再回退到应用启动图标。启动图标是全彩的,并且可能会渲染成纯白色方块,因为 Android 要求通知图标必须是单色的。

Are you using this library in an existing React Native app?

如果你没有使用 Continuous Native Generation (CNG),或者你是在手动使用原生 ios 项目,那么你需要将 NSLocationAlwaysAndWhenInUseUsageDescriptionNSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 键添加到项目的 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
    当出现新的地理围栏事件时,系统会重新启动已终止的应用。

后台定位配置 
iOS

要在 iOS 上运行后台定位,你需要在应用的 Info.plist 文件中将 location 值添加到 UIBackgroundModes 数组里。

如果你使用的是 CNG,所需的 UIBackgroundModes 配置会在 prebuild 时自动应用。

在 iOS 上手动配置 UIBackgroundModes

如果你没有使用 Continuous Native Generation (CNG),或者你使用的是原生 iOS 项目,那么你需要将以下内容添加到 Expo.plist 文件中:

ios/project-name/Supporting/Expo.plist
<key>UIBackgroundModes</key> <array> <string>location</string> </array>

后台定位方法

要使用后台定位方法,需要满足以下条件:

  • 必须授予位置权限。
  • 必须在顶层作用域中使用 TaskManager.defineTask 定义后台定位任务。
  • iOS
    Info.plist 文件中必须指定 "location" 后台模式。请参见后台定位配置
  • iOS
    由于 Expo Go 应用不支持后台定位,你必须使用开发构建

地理围栏方法

要使用地理围栏方法,需要满足以下条件:

  • 必须授予位置权限。
  • 必须在顶层作用域中使用 TaskManager.defineTask 定义地理围栏任务。

使用地理围栏时,适用以下平台差异:

  • Android
    每个应用最多允许100 个活动地理围栏。
  • iOS
    Expo Location 会在应用启动时报告已注册地理围栏的初始状态。
  • iOS
    可同时监测的 regions 数量上限为 20 个

后台权限

要在后台使用位置追踪或地理围栏,你必须请求相应的权限:

Expo 与 iOS 权限

iOS 权限分为 When In UseAlways 两类,并映射到 Expo 的前台和后台位置权限,请求方式如下:

检测 “允许一次” 与 “使用 App 期间允许” 的区别

遗憾的是,iOS 无法提供一种方式来判断用户选择的是 Allow Once 还是 Allow While Using the App。这两种响应都会导致 When In Use 授权。

如果用户选择了 Allow Once,并且你在同一会话中随后调用了 requestBackgroundPermissionsAsync,系统不会再显示另一个提示。相反,这个请求会静默失败,返回的后台权限状态将是被拒绝

处理 “允许一次” 的场景

如果你怀疑用户选择了 Allow Once,而你需要请求后台权限,那么他们必须在设置应用中手动启用后台定位。你可以使用 Linking 在应用内打开设置应用:

import { Linking } from 'react-native'; function openSettings() { Linking.openURL('app-settings:'); }

渐进式权限请求

可以先请求前台定位权限,然后在稍后再请求后台定位权限。这种方式可以通过仅在必要时请求权限来改善用户体验。

直接请求后台权限

如果你在未先请求前台权限的情况下调用 requestBackgroundPermissionsAsync,iOS 会将其视为同时请求 When In UseAlways 授权。随后系统会提示用户授予 When In Use 访问权限,而当系统判断需要 Always 授权时,会显示 Always 授权提示。

请记住,用户也可以选择仅授予你的应用 When In Use 授权。你必须始终准备好在 When In Use 权限下运行。

延迟位置

当使用后台位置时,你可以配置位置管理器以延迟更新。这有助于通过降低更新频率来节省电量。你可以将更新设置为仅在设备移动了某个特定距离或经过指定时间间隔后触发。

延迟更新通过 LocationTaskOptions 进行配置,使用 deferredUpdatesDistancedeferredUpdatesIntervaldeferredTimeout 属性。

用法

如果你正在使用 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 模拟器。在其中,前往 设置 > 位置,并启用 使用位置信息

如果你没有在模拟器中收到位置信息,你可能需要关闭 提高定位精度 设置。这将关闭 Wi-Fi 定位,仅使用 GPS。然后你可以通过模拟器使用 GPS 数据来调整位置。

对于 Android 12 及更高版本,前往 设置 > 位置 > 位置服务 > Google 定位精度,并关闭 提高定位精度。对于 Android 11 及更低版本,前往 设置 > 位置 > 高级 > Google 定位精度,并关闭 Google 定位精度

iOS 模拟器

打开 Simulator 后,前往 功能 > 位置,并选择除 之外的任意选项。

API

import * as Location from 'expo-location';

Hooks

useBackgroundPermissions(options)

Android
iOS
Web
ParameterType
options(optional)PermissionHookOptions<object>

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

Returns:
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]

Example

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

useForegroundPermissions(options)

Android
iOS
Web
ParameterType
options(optional)PermissionHookOptions<object>

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

Returns:
[LocationPermissionResponse | null, RequestPermissionMethod<LocationPermissionResponse>, GetPermissionMethod<LocationPermissionResponse>]

Example

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

useMotionActivityPermissions(options)

Android
iOS
ParameterType
options(optional)PermissionHookOptions<object>

Checks or requests permissions for motion activity detection. This uses both requestMotionActivityPermissionsAsync and getMotionActivityPermissionsAsync to interact with the permissions.

Returns:
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]

Example

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

Methods

Location.enableNetworkProviderAsync()

Android

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.

Returns:
Promise<void>

A promise resolving as soon as the user accepts the dialog. Rejects if denied.

Location.geocodeAsync(address)

Android
iOS
ParameterTypeDescription
addressstring

A string representing address, eg. "Baker Street London".


Geocode an address string to latitude-longitude location.

On Android, you must request location permissions with requestForegroundPermissionsAsync before geocoding can be used.

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

Location.getBackgroundPermissionsAsync()

Android
iOS
Web

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

Returns:
Promise<PermissionResponse>

A promise that fulfills with an object of type PermissionResponse.

Location.getCurrentPositionAsync(options)

Android
iOS
Web
ParameterType
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.

A promise which fulfills with an object of type LocationObject.

Location.getForegroundPermissionsAsync()

Android
iOS
Web

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

A promise that fulfills with an object of type LocationPermissionResponse.

Location.getHeadingAsync()

Android
iOS
Web

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.

Location.getLastKnownPositionAsync(options)

Android
iOS
Web
ParameterType
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.

Returns:
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.

Location.getMotionActivityAsync()

Android
iOS

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.

a promise which fulfills with a MotionActivityObject.

Location.getMotionActivityPermissionsAsync()

Android
iOS

Checks user's permissions for accessing motion activity data.

Returns:
Promise<PermissionResponse>

A promise that fulfills with an object of type PermissionResponse.

Location.getProviderStatusAsync()

Android
iOS
Web

Check status of location providers.

A promise which fulfills with an object of type LocationProviderStatus.

Location.hasServicesEnabledAsync()

Android
iOS
Web

Checks whether location services are enabled by the user.

Returns:
Promise<boolean>

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

Location.hasStartedGeofencingAsync(taskName)

Android
iOS
Web
ParameterTypeDescription
taskNamestring

Name of the geofencing task to check.


Returns:
Promise<boolean>

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

Location.hasStartedLocationUpdatesAsync(taskName)

Android
iOS
Web
ParameterTypeDescription
taskNamestring

Name of the location task to check.


Returns:
Promise<boolean>

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

Location.installWebGeolocationPolyfill()

Android
iOS
Web

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

Returns:
void

Location.isBackgroundLocationAvailableAsync()

Android
iOS
Web
Returns:
Promise<boolean>

Location.requestBackgroundPermissionsAsync()

Android
iOS
Web

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.

Returns:
Promise<PermissionResponse>

A promise that fulfills with an object of type PermissionResponse.

Location.requestForegroundPermissionsAsync()

Android
iOS
Web

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

A promise that fulfills with an object of type LocationPermissionResponse.

Location.requestMotionActivityPermissionsAsync()

Android
iOS

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.

Returns:
Promise<PermissionResponse>

a promise that fulfills with an object of type PermissionResponse.

Location.reverseGeocodeAsync(location)

Android
iOS
ParameterTypeDescription
locationPick<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.

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

Location.startGeofencingAsync(taskName, regions)

Android
iOS
Web
ParameterTypeDescription
taskNamestring

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. See GeofencingEventType.
  • region - Object containing details about updated region. See LocationRegion for more details.
Returns:
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); } });

Location.startLocationUpdatesAsync(taskName, options)

Android
iOS
Web
ParameterTypeDescription
taskNamestring

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.
Returns:
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); });

Location.stopGeofencingAsync(taskName)

Android
iOS
Web
ParameterTypeDescription
taskNamestring

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.

Returns:
Promise<void>

A promise resolving as soon as the task is unregistered.

Location.stopLocationUpdatesAsync(taskName)

Android
iOS
Web
ParameterTypeDescription
taskNamestring

Name of the background location task to stop.


Stops location updates for specified task.

Returns:
Promise<void>

A promise resolving as soon as the task is unregistered.

Location.watchHeadingAsync(callback, errorHandler)

Android
iOS
ParameterTypeDescription
callbackLocationHeadingCallback

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.

A promise which fulfills with a LocationSubscription object.

Location.watchMotionActivityAsync(callback, errorHandler)

Android
iOS
ParameterTypeDescription
callbackMotionActivityCallback

This function is called on each motion activity update. It receives an object of type MotionActivityObject as the first argument.

errorHandler(optional)LocationErrorCallback

This function is called if the platform reports an error (for example, when activity recognition permission is denied). It receives a string message as the first argument.


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.

a promise which fulfills with a LocationSubscription object.

Location.watchPositionAsync(options, callback, errorHandler)

Android
iOS
Web
ParameterTypeDescription
optionsLocationOptions
-
callbackLocationCallback

This function is called on each location update. It receives an object of type LocationObject 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 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.

A promise which fulfills with a LocationSubscription object.

Types

LocationCallback(location)

Android
iOS
Web

Represents watchPositionAsync callback.

ParameterType
locationLocationObject
Returns:

any

LocationErrorCallback(reason)

Android
iOS
Web

Error callback for location methods.

ParameterType
reasonstring
Returns:

void

LocationGeocodedAddress

Android
iOS
Web

Type representing a result of reverseGeocodeAsync.

PropertyTypeDescription
citystring | null

City name of the address.

countrystring | null

Localized country name of the address.

districtstring | null

Additional city-level information like district name.

formattedAddressstring | null
Only for:
Android

Composed string of the address components, for example, "111 8th Avenue, New York, NY".

isoCountryCodestring | null

Localized (ISO) country code of the address, if available.

namestring | null

The name of the placemark, for example, "Tower Bridge".

postalCodestring | null

Postal code of the address.

regionstring | null

The state or province associated with the address.

streetstring | null

Street name of the address.

streetNumberstring | null

Street number of the address.

subregionstring | null

Additional information about administrative area.

timezonestring | null
Only for:
iOS

The timezone identifier associated with the address.

LocationGeocodedLocation

Android
iOS
Web

Type representing a result of geocodeAsync.

PropertyTypeDescription
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.

latitudenumber

The latitude in degrees.

longitudenumber

The longitude in degrees.

LocationHeadingCallback(location)

Android
iOS
Web

Represents watchHeadingAsync callback.

ParameterType
locationLocationHeadingObject
Returns:

any

LocationHeadingObject

Android
iOS
Web

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

PropertyTypeDescription
accuracynumber

Level 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
magHeadingnumber

Measure of magnetic north in degrees.

trueHeadingnumber

Measure of true north in degrees (needs location permissions, will return -1 if not given).

LocationLastKnownOptions

Android
iOS
Web

Type representing options object that can be passed to getLastKnownPositionAsync.

PropertyTypeDescription
maxAge(optional)number

A number of milliseconds after which the last known location starts to be invalid and thus null is returned.

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 null is returned.

LocationObject

Android
iOS
Web

Type representing the location object.

PropertyTypeDescription
coordsLocationObjectCoords

The coordinates of the position.

mocked(optional)boolean
Only for:
Android

Whether the location coordinates is mocked or not.

timestampnumber

The time at which this position information was obtained, in milliseconds since epoch.

LocationObjectCoords

Android
iOS
Web

Type representing the location GPS related data.

PropertyTypeDescription
accuracynumber | null

The radius of uncertainty for the location, measured in meters. Can be null on Web if it's not available.

altitudenumber | null

The altitude in meters above the WGS 84 reference ellipsoid. Can be null on Web if it's not available.

altitudeAccuracynumber | null

The accuracy of the altitude value, in meters. Can be null on Web if it's not available.

headingnumber | 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.

latitudenumber

The latitude in degrees.

longitudenumber

The longitude in degrees.

speednumber | null

The instantaneous speed of the device in meters per second. Can be null on Web if it's not available.

LocationOptions

Android
iOS
Web

Type representing options argument in getCurrentPositionAsync.

PropertyTypeDescription
accuracy(optional)Accuracy

Location manager accuracy. Pass one of Accuracy enum values. For low-accuracies the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).

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 accuracy option.

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 accuracy option.

LocationPermissionResponse

Android
iOS
Web

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

Type: PermissionResponse extended by:

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

LocationProviderStatus

Android
iOS
Web

Represents the object containing details about location provider.

PropertyTypeDescription
backgroundModeEnabledboolean
-
gpsAvailable(optional)boolean
Only for:
Android

Whether the GPS provider is available. If true the location data will come from GPS, especially for requests with high accuracy.

locationServicesEnabledboolean

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 true the location data will come from cellular network, especially for requests with low accuracy.

passiveAvailable(optional)boolean
Only for:
Android

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

LocationRegion

Android
iOS
Web

Type representing geofencing region object.

PropertyTypeDescription
identifier(optional)string

The identifier of the region object. Defaults to auto-generated UUID hash.

latitudenumber

The latitude in degrees of region's center point.

longitudenumber

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
radiusnumber

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.

LocationSubscription

Android
iOS
Web

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

PropertyTypeDescription
remove() => void

Call this function with no arguments to remove this subscription. The callback will no longer be called for location updates.

LocationTaskOptions

Android
iOS
Web

Type representing background location task options.

Type: LocationOptions extended by:

PropertyTypeDescription
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 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
Only for:
iOS

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

Default:false

LocationTaskServiceOptions

Android
iOS
Web
PropertyTypeDescription
killServiceOnDestroy(optional)boolean

Boolean value whether to destroy the foreground service if the app is killed.

notificationBodystring

Subtitle of the foreground service notification.

notificationColor(optional)string

Color of the foreground service notification. Accepts #RRGGBB and #AARRGGBB hex formats.

notificationTitlestring

Title of the foreground service notification.

MotionActivityCallback(activity)

Android
iOS
Web

Represents the watchMotionActivityAsync callback.

ParameterType
activityMotionActivityObject
Returns:

any

MotionActivityObject

Android
iOS
Web

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); }
PropertyTypeDescription
activitiesRecord<MotionActivityType, MotionActivityState>

An object keyed by MotionActivityType, each value being a MotionActivityState.

timestampnumber

The time at which the activity snapshot was taken, in milliseconds since Unix epoch.

MotionActivityState

Android
iOS
Web

Detection state for a single activity type. When detected is false, confidence is always Low.

PropertyTypeDescription
confidenceMotionActivityConfidence

Confidence level of the detection. On Android, each activity type has its own confidence derived from the DetectedActivity probability value. On iOS, this is the overall reading confidence from CMMotionActivityConfidence, shared by all detected activities.

detectedboolean

Whether this activity was detected.

PermissionDetailsLocationAndroid

Android
iOS
Web
PropertyTypeDescription
accuracy'fine' | 'coarse' | 'none'

Indicates the type of location provider.

PermissionDetailsLocationIOS

Android
iOS
Web
PropertyTypeDescription
accuracy'full' | 'reduced'
Only for:
iOS 14+

The accuracy authorization granted by the user. 'full' means the user has granted precise location access, 'reduced' means the app can only access approximate location. Below iOS 14 always returns 'full'.

scope'whenInUse' | 'always' | 'none'

The scope of granted permission. Indicates when it's possible to use location.

PermissionExpiration

Android
iOS
Web

Literal type: union

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never' | number

PermissionHookOptions

Android
iOS
Web

Literal type: union

Acceptable values are: PermissionHookBehavior | Options

PermissionResponse

Android
iOS
Web

An object obtained by permissions get and request functions.

PropertyTypeDescription
canAskAgainboolean

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.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.

Enums

Accuracy

Android
iOS
Web

Enum with available location accuracies.

Lowest

Accuracy.Lowest = 1

Accurate to the nearest three kilometers.

Low

Accuracy.Low = 2

Accurate to the nearest kilometer.

Balanced

Accuracy.Balanced = 3

Accurate to within one hundred meters.

High

Accuracy.High = 4

Accurate to within ten meters of the desired target.

Highest

Accuracy.Highest = 5

The best level of accuracy available.

BestForNavigation

Accuracy.BestForNavigation = 6

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

ActivityType

Android
iOS
Web

Enum with available activity types of background location tracking.

Other

ActivityType.Other = 1

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

AutomotiveNavigation

ActivityType.AutomotiveNavigation = 2

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

Fitness

ActivityType.Fitness = 3

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

OtherNavigation

ActivityType.OtherNavigation = 4

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

Airborne

iOS
ActivityType.Airborne = 5

Intended for airborne activities. Fall backs to ActivityType.Other if unsupported.

GeofencingEventType

Android
iOS
Web

A type of the event that geofencing task can receive.

Enter

GeofencingEventType.Enter = 1

Emitted when the device entered observed region.

Exit

GeofencingEventType.Exit = 2

Occurs as soon as the device left observed region

GeofencingRegionState

Android
iOS
Web

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

Unknown

GeofencingRegionState.Unknown = 0

Indicates that the device position related to the region is unknown.

Inside

GeofencingRegionState.Inside = 1

Indicates that the device is inside the region.

Outside

GeofencingRegionState.Outside = 2

Inverse of inside state.

MotionActivityConfidence

Android
iOS
Web

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.

Low

MotionActivityConfidence.Low = 0

The activity determination has low confidence.

Medium

MotionActivityConfidence.Medium = 1

The activity determination has medium confidence.

High

MotionActivityConfidence.High = 2

The activity determination has high confidence.

MotionActivityType

Android
iOS
Web

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).

Automotive

MotionActivityType.Automotive = "automotive"

The device is in a motorized vehicle (car, bus, train, and so on).

Cycling

MotionActivityType.Cycling = "cycling"

The user is riding a bicycle.

Running

MotionActivityType.Running = "running"

The user is running.

Stationary

MotionActivityType.Stationary = "stationary"

The device is not moving.

Unknown

MotionActivityType.Unknown = "unknown"

The activity cannot be determined.

Walking

MotionActivityType.Walking = "walking"

The user is walking.

PermissionStatus

Android
iOS
Web

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.

权限

Android

当你安装 expo-location 模块时,它会自动添加以下权限:

  • ACCESS_COARSE_LOCATION:用于获取大致的设备位置
  • ACCESS_FINE_LOCATION:用于获取精确的设备位置

以下权限是可选的:

Android permissionDescription

ACCESS_COARSE_LOCATION

Allows an app to access approximate location.

ACCESS_FINE_LOCATION

Allows an app to access precise location.

FOREGROUND_SERVICE

Allows a regular application to use Service.startForeground.

FOREGROUND_SERVICE_LOCATION

Allows a regular application to use Service.startForeground with the type "location".

ACCESS_BACKGROUND_LOCATION

Allows an app to access location in the background.

排除某项权限

当你的 Expo 项目不需要包含某些特定权限时,你可以省略它。例如,如果你的应用不需要访问精确位置,你可以排除 ACCESS_FINE_LOCATION 权限。

另一个例子可以用可用的位置精度来说明。Android 将大致位置精度定义为约 3 平方公里以内,将精确位置精度定义为约 50 米以内。例如,如果位置精度值为 ,你可以排除 ACCESS_FINE_LOCATION 权限。要了解有关位置精度等级的更多信息,请参阅 Android 文档

要详细了解如何排除权限,请参阅排除 Android 权限

iOS

此库使用以下用途说明键:

Info.plist keyDescription

NSLocationAlwaysAndWhenInUseUsageDescription

A message that tells the user why the app is requesting access to the user’s location information at all times.

NSLocationAlwaysUsageDescription

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.

NSLocationWhenInUseUsageDescription

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.

NSLocationAlwaysUsageDescription 已被弃用,自 iOS 11 起应改用 NSLocationAlwaysAndWhenInUseUsageDescription