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:
~58.0.13

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

安装

🌐 Installation

Terminal
- npx expo install expo-location
- yarn expo install expo-location
- pnpm expo install expo-location
- bun expo install expo-location

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

应用配置中的配置

🌐 Configuration in app config

如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 配置插件 来配置 expo-location。该插件允许你配置无法在运行时设置并且需要构建新的应用二进制文件才能生效的各种属性。如果你的应用不使用 CNG,那么你需要手动配置该库。

🌐 You can configure expo-location using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-location", { "locationAlwaysAndWhenInUsePermission": "Allow $(PRODUCT_NAME) to use your location." } ] ] } }

Configurable properties

NameDefaultDescription
locationAlwaysAndWhenInUsePermission"Allow $(PRODUCT_NAME) to use your location"
Only for: 
iOS

A string to set the NSLocationAlwaysAndWhenInUseUsageDescription permission message.

locationAlwaysPermission"Allow $(PRODUCT_NAME) to use your location"
Deprecated
 • 
Only for: 
iOS

A string to set the NSLocationAlwaysUsageDescription permission message.

locationWhenInUsePermission"Allow $(PRODUCT_NAME) to use your location"
Only for: 
iOS

A string to set the NSLocationWhenInUseUsageDescription permission message.

motionUsagePermission"Allow $(PRODUCT_NAME) to detect your current motion activity"
Only for: 
iOS

A string to set the NSMotionUsageDescription permission message shown when getMotionActivityAsync or watchMotionActivityAsync is called for the first time.

isIosBackgroundLocationEnabledfalse
Only for: 
iOS

A boolean to enable location in the UIBackgroundModes in Info.plist.

isAndroidBackgroundLocationEnabledfalse
Only for: 
Android

A boolean to enable the ACCESS_BACKGROUND_LOCATION permission.

isAndroidForegroundServiceEnabled-
Only for: 
Android

A boolean to enable the FOREGROUND_SERVICE permission and FOREGROUND_SERVICE_LOCATION (required on Android 14 and later when running a location foreground service). Defaults to true if isAndroidBackgroundLocationEnabled is true, otherwise false.

androidForegroundServiceIcon-
Only for: 
Android

Local path to an image to use as the icon for the foreground service started by startLocationUpdatesAsync. 96x96 all-white png with transparency. If not set, falls back to the notification_icon drawable (if configured via expo-notifications config plugin), then to the app launcher icon. The launcher icon is full-color and may render as a solid white square since Android requires notification icons to be monochrome.

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

如果你没有使用连续原生生成 (CNG) 或者你是手动使用原生 iOS 项目,那么你需要在项目的 ios/[app]/Info.plist 中添加 NSLocationAlwaysAndWhenInUseUsageDescription、NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription 键:

🌐 If you're not using Continuous Native Generation (CNG) or you're using native ios project manually, then you need to add the NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription keys to your project's ios/[app]/Info.plist:

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>Allow $(PRODUCT_NAME) to use your location</string> <key>NSLocationAlwaysUsageDescription</key> <string>Allow $(PRODUCT_NAME) to use your location</string> <key>NSLocationWhenInUseUsageDescription</key> <string>Allow $(PRODUCT_NAME) to use your location</string>

背景位置

🌐 Background location

后台位置功能允许你的应用在后台运行时接收位置更新,包括通过地理围栏进行的位置更新和区域监控。此功能受平台 API 限制和系统约束的影响:

🌐 Background location allows your app to receive location updates while it is running in the background and includes both location updates and region monitoring through geofencing. This feature is subject to platform API limitations and system constraints:

  • 如果用户终止应用,后台定位将停止。
  • 如果用户重新启动应用,后台定位将恢复。
  • Android
    由于平台限制,已终止的应用在发生位置或地理围栏事件时不会自动重新启动。
  • iOS
    当发生新的地理围栏事件时,系统将重新启动已终止的应用。

背景位置配置 
iOS

🌐 Background location configuration 

iOS

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

🌐 To be able to run background location on iOS, you need to add the location value to the UIBackgroundModes array in your app's Info.plist file.

如果你正在使用 CNG,所需的 UIBackgroundModes 配置将会由预构建自动应用。

在 iOS 上手动配置 UIBackgroundModes

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

🌐 If you're not using Continuous Native Generation (CNG) or you're using a native iOS project, then you'll need to add the following to your Expo.plist file:

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

后台定位方法

🌐 Background location methods

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

🌐 To use Background Location methods, the following requirements apply:

  • 必须授予位置权限。
  • 后台位置任务必须在顶层作用域中定义,使用 TaskManager.defineTask。
  • 必须在 Info.plist 文件中指定 <PlatformTag platform="ios" className="float-left" /> "location" 的后台模式。请参阅 后台位置配置。
  • iOS
    你必须使用 开发版本 才能使用后台定位,因为 Expo Go 应用不支持此功能。

地理围栏方法

🌐 Geofencing methods

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

🌐 To use Geofencing methods, the following requirements apply:

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

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

🌐 When using Geofencing, the following platform differences apply:

  • Android
    每个应用允许最多100个活动地理围栏。
  • iOS
    Expo 位置将在应用启动时报告已注册地理围栏的初始状态。
  • iOS
    可以同时监控的 regions 有 20 个限制。

后台权限

🌐 Background permissions

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

🌐 To use location tracking or Geofencing in the background, you must request the appropriate permissions:

  • 在 Android 上,你必须同时请求前台和后台权限。
  • 在 iOS 上,必须使用 requestBackgroundPermissionsAsync 并选择 Always 选项来授予权限。
Expo 和 iOS 权限

iOS permissions are divided into the two categories When In Use and Always and map to Expo's foreground and background location permissions requested via:

检测“仅允许一次”与“使用应用时允许”

不幸的是,iOS 不提供方法来检测用户选择了 Allow Once 还是 Allow While Using the App。两种选择都会导致 When In Use 授权。

🌐 Unfortunately, iOS does not provide a way to detect whether the user selected Allow Once or Allow While Using the App. Both responses result in When In Use authorization.

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

🌐 If the user selected Allow Once and you subsequently call requestBackgroundPermissionsAsync in the same session, the system will not show another prompt. Instead, the request will silently fail, and the returned background permission status will be denied.

处理“仅允许一次”情况

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

🌐 If you suspect the user selected Allow Once and needs to request background permissions, they must manually enable background location in the Settings app. You can use Linking to open the Settings app within your app:

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

逐步权限请求

可以先请求前台位置访问权限,然后再请求后台位置访问权限。这可以通过仅在必要时请求权限来改善用户体验。

🌐 It is possible to request foreground location access first and then ask for background location access later. This can improve the user experience by requesting permissions only when necessary.

直接请求后台权限

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

🌐 If you call requestBackgroundPermissionsAsync without first requesting foreground permissions, iOS treats it as a request for both When In Use and Always authorization. The system will then prompt the user for When In Use access, and the Always authorization prompt will be displayed when the system determines that Always authorization is required.

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

🌐 Remember that the user has the option of granting your app When In Use authorization instead. You must always be prepared to run with When In Use permission.

延迟位置

🌐 Deferred locations

在使用后台定位时,你可以配置位置管理器以延迟更新。这有助于通过减少更新频率来节省电量。你可以设置仅在设备移动一定距离或经过指定的时间间隔后触发更新。

🌐 When using background locations, you can configure the location manager to defer updates. This helps save battery by reducing update frequency. You can set updates to trigger only after the device has moved a certain distance or after a specified time interval.

延迟更新通过 LocationTaskOptions 使用 deferredUpdatesDistance、deferredUpdatesInterval 和 deferredTimeout 属性进行配置。

🌐 Deferred updates are configured through LocationTaskOptions using the deferredUpdatesDistance, deferredUpdatesInterval and deferredTimeout properties.

用法

🌐 Usage

如果你正在使用 Android 模拟器或 iOS 模拟器,请确保已启用位置。

🌐 If you're using the Android Emulator or iOS Simulator, ensure that Location is enabled.

Location
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( 'Oops, this will not work on Snack in an Android Emulator. Try it on your device!' ); return; } let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { setErrorMsg('Permission to access location was denied'); return; } let location = await Location.getCurrentPositionAsync({}); setLocation(location); } getCurrentLocation(); }, []); let text = 'Waiting...'; 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', }, });

启用模拟器位置

🌐 Enable emulator location

安卓模拟器

🌐 Android Emulator

打开 Android Studio,并启动 Android 模拟器。在模拟器中,进入 设置 > 位置,并启用 使用位置。

🌐 Open Android Studio, and launch the Android Emulator. Inside it, go to Settings > Location and enable Use location.

如果你在模拟器中无法接收位置,你可能需要关闭提高定位精度设置。这将关闭 Wi-Fi 定位,仅使用 GPS。然后你可以通过模拟器使用 GPS 数据来操作位置。

🌐 If you don't receive the locations in the emulator, you may have to turn off the Improve Location Accuracy setting. This will turn off Wi-Fi location and only use GPS. Then you can manipulate the location with GPS data through the emulator.

对于 Android 12 及以上版本,进入 设置 > 位置 > 位置服务 > Google 位置精确度,然后关闭 提高位置精确度。对于 Android 11 及以下版本,进入 设置 > 位置 > 高级 > Google 位置精确度,然后关闭 Google 位置精确度。

🌐 For Android 12 and higher, go to Settings > Location > Location Services > Google Location Accuracy, and turn off Improve Location Accuracy. For Android 11 and lower, go to Settings > Location > Advanced > Google Location Accuracy, and turn off Google Location Accuracy.

iOS 模拟器

🌐 iOS Simulator

打开设备中心后,进入 设备 > 位置,选择除 无 之外的任何选项。

🌐 With Device Hub open, go to Device > Location and choose any option besides None.

应用接口

🌐 API

import * as Location from 'expo-location';

No API data file found, sorry!

权限

🌐 Permissions

安卓

🌐 Android

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

🌐 When you install the expo-location module, it automatically adds the following permissions:

  • ACCESS_COARSE_LOCATION:用于近似设备位置
  • ACCESS_FINE_LOCATION:用于精确定位设备

以下权限是可选的:

🌐 The following permissions are optional:

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.

不包括许可

🌐 Excluding a permission

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

🌐 When your Expo project doesn't benefit from having particular permission included, you can omit it. For example, if your application doesn't need access to the precise location, you can exclude the ACCESS_FINE_LOCATION permission.

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

🌐 Another example can be stated using available location accuracies. Android defines the approximate location accuracy estimation within about 3 square kilometers, and the precise location accuracy estimation within about 50 meters. For example, if the location accuracy value is Low, you can exclude ACCESS_FINE_LOCATION permission. To learn more about levels of location accuracies, see Android documentation.

想了解更多关于如何排除权限的信息,请参阅 排除 Android 权限。

🌐 To learn more on how to exclude permission, see Excluding Android permissions.

iOS

该库使用以下用法描述键:

🌐 The following usage description keys are used by this library:

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。