首页指南参考教程

Expo 定位 iconExpo 定位

GitHub

npm

提供读取地理位置信息、轮询当前位置或从设备订阅位置更新事件的库。

Android
iOS
Web

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

¥expo-location allows reading geolocation information from the device. Your app can poll for the current location or subscribe to location update events.

安装

¥Installation

Terminal
npx expo install expo-location

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

app.json/app.config.js 中的配置

¥Configuration in app.json/app.config.js

如果你在项目中使用配置插件(EAS 构建npx expo run:[android|ios]),则可以使用其内置的 配置插件 配置 expo-location。该插件允许你配置无法在运行时设置的各种属性,并且需要构建新的应用二进制文件才能生效。

¥You can configure expo-location using its built-in config plugin if you use config plugins in your project (EAS Build or npx expo run:[android|ios]). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect.

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

isIosBackgroundLocationEnabledfalseOnly for:
iOS

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

isAndroidBackgroundLocationEnabledfalseOnly 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. Defaults to true if isAndroidBackgroundLocationEnabled is true, otherwise false.

Are you using this library in a bare React Native app?

了解如何在 expo-location 存储库中的安装说明 文件中配置原生项目。

¥Learn how to configure the native projects in the installation instructions in the expo-location repository.

后台定位方法

¥Background Location methods

警告:后台位置跟踪支持按原样提供,不保证在所有情况下都能正常工作。我们目前没有优先考虑资源来改进它,但我们希望将来能够这样做。你可能想使用 react-native-background-geolocation - 它需要购买许可证,并且是一个维护良好且受支持的库,其中包含配置插件。

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

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

  • 必须授予位置权限。在 iOS 上,必须使用 Always 选项授予它。

    ¥Location permissions must be granted. On iOS it must be granted with Always option.

  • (仅限 iOS)"location" 后台模式必须在 Info.plist 文件中指定。参见 后台任务配置指南

    ¥**(iOS only)** "location" background mode must be specified in Info.plist file. See background tasks configuration guide.

  • 后台位置任务必须在顶层范围中使用 TaskManager.defineTask 进行定义。

    ¥Background location task must be defined in the top-level scope, using TaskManager.defineTask.

地理围栏方法

¥Geofencing methods

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

¥To use Geofencing methods, the following requirements apply:

  • 必须授予位置权限。在 iOS 上,必须使用 Always 选项授予它。

    ¥Location permissions must be granted. On iOS it must be granted with Always option.

  • 地理围栏任务必须使用 TaskManager.defineTask 在顶层范围中定义。

    ¥The Geofencing task must be defined in the top-level scope, using TaskManager.defineTask.

  • 在 iOS 上,有一个 限制为 20 regions 可以同时监控。

    ¥On iOS, there is a limit of 20 regions that can be simultaneously monitored.

用法

¥Usage

如果你使用的是 Android 模拟器或 iOS 模拟器,请确保 位置已启用

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

Location
import React, { useState, useEffect } from 'react';
import { Platform, Text, View, StyleSheet } from 'react-native';
%%placeholder-start%%%%placeholder-end%%import Device from 'expo-device';
import * as Location from 'expo-location';

export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    (async () => {
      %%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);
    })();
  }, []);

  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 Simulator open, go to Features > Location and choose any option besides None.

API

import * as Location from 'expo-location';

Hooks

useBackgroundPermissions(options)

NameTypeDescription
options
(optional)
PermissionHookOptions<object>-

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

Example

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

Returns

  • [null | PermissionResponse, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]

useForegroundPermissions(options)

NameTypeDescription
options
(optional)
PermissionHookOptions<object>-

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

Example

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

Returns


Methods

Location.enableNetworkProviderAsync()

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, options)

NameTypeDescription
addressstring

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

options
(optional)
LocationGeocodingOptions-

Geocode an address string to latitude-longitude location.

Note: Using the Geocoding web api is no longer supported. Use Place Autocomplete instead.

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.

On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.

Returns

  • Promise<LocationGeocodedLocation[]>

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

Location.getBackgroundPermissionsAsync()

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)

NameTypeDescription
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 Location.getLastKnownPositionAsync if you expect to get a quick response and high accuracy is not required.

Returns

  • Promise<LocationObject>

A promise which fulfills with an object of type LocationObject.

Location.getForegroundPermissionsAsync()

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

Returns

  • Promise<LocationPermissionResponse>

A promise that fulfills with an object of type PermissionResponse.

Location.getHeadingAsync()

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.

Returns

  • Promise<LocationHeadingObject>

A promise which fulfills with an object of type LocationHeadingObject.

Location.getLastKnownPositionAsync(options)

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

Deprecated. Use getForegroundPermissionsAsync or getBackgroundPermissionsAsync instead.

Location.getPermissionsAsync()

Checks user's permissions for accessing location.

Returns

  • Promise<LocationPermissionResponse>

A promise that fulfills with an object of type LocationPermissionResponse.

Location.getProviderStatusAsync()

Check status of location providers.

Returns

  • Promise<LocationProviderStatus>

A promise which fulfills with an object of type LocationProviderStatus.

Location.hasServicesEnabledAsync()

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)

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

NameTypeDescription
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()

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

Returns

  • void

Location.isBackgroundLocationAvailableAsync()

Returns

  • Promise<boolean>

Location.requestBackgroundPermissionsAsync()

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

Returns

  • Promise<PermissionResponse>

A promise that fulfills with an object of type PermissionResponse.

Location.requestForegroundPermissionsAsync()

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

Returns

  • Promise<LocationPermissionResponse>

A promise that fulfills with an object of type PermissionResponse.

Deprecated. Use requestForegroundPermissionsAsync or requestBackgroundPermissionsAsync instead.

Location.requestPermissionsAsync()

Asks the user to grant permissions for location.

Returns

  • Promise<LocationPermissionResponse>

A promise that fulfills with an object of type LocationPermissionResponse.

Location.reverseGeocodeAsync(location, options)

NameTypeDescription
locationPick<LocationGeocodedLocation, 'latitude' | 'longitude'>

An object representing a location.

options
(optional)
LocationGeocodingOptions-

Reverse geocode a location to postal address.

Note: Using the Geocoding web api is no longer supported. Use Place Autocomplete instead.

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.

On Android, you must request a location permission (Permissions.LOCATION) from the user before geocoding can be used.

Returns

  • Promise<LocationGeocodedAddress[]>

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

Deprecated. The Geocoding web api is no longer available from SDK 49 onwards. Use Place Autocomplete instead.

Location.setGoogleApiKey(_apiKey)

NameTypeDescription
_apiKeystring

Google API key obtained from Google API Console. This API key must have Geocoding API enabled, otherwise your geocoding requests will be denied.


Returns

  • void

Location.startGeofencingAsync(taskName, regions)

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

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);
  }
});

Returns


A promise resolving as soon as the task is registered.

Location.startLocationUpdatesAsync(taskName, options)

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

Returns


A promise resolving once the task with location updates is registered.

Location.stopGeofencingAsync(taskName)

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

NameTypeDescription
taskNamestring

Name of the background location task to stop.


Stops geofencing for specified task.

Returns

  • Promise<void>

A promise resolving as soon as the task is unregistered.

Location.watchHeadingAsync(callback)

NameTypeDescription
callbackLocationHeadingCallback

This function is called on each compass update. It receives an object of type LocationHeadingObject as the first argument.


Subscribe to compass updates from the device.

Returns

  • Promise<LocationSubscription>

A promise which fulfills with a LocationSubscription object.

Location.watchPositionAsync(options, callback)

NameTypeDescription
optionsLocationOptions-
callbackLocationCallback

This function is called on each location update. It receives an object of type LocationObject as the first argument.


Subscribe to location updates from the device. Please note that updates will only occur while the application is in the foreground. To get location updates while in background you'll need to use Location.startLocationUpdatesAsync.

Returns

  • Promise<LocationSubscription>

A promise which fulfills with a LocationSubscription object.

Interfaces

PermissionResponse

An object obtained by permissions get and request functions.

PermissionResponse Properties

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


Types

LocationCallback()

Represents watchPositionAsync callback.

NameTypeDescription
locationLocationObject-

LocationGeocodedAddress

Type representing a result of reverseGeocodeAsync.

NameTypeDescription
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 | nullOnly 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 | nullOnly for:
iOS

The timezone identifier associated with the address.

LocationGeocodedLocation

Type representing a result of geocodeAsync.

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

LocationGeocodingOptions

An object of options for forward and reverse geocoding.

NameTypeDescription
useGoogleMaps
(optional)
boolean

Whether to force using Google Maps API instead of the native implementation. Used by default only on Web platform. Requires providing an API key by setGoogleApiKey.

LocationHeadingCallback()

Represents watchHeadingAsync callback.

NameTypeDescription
locationLocationHeadingObject-

LocationHeadingObject

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

NameTypeDescription
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

Type representing options object that can be passed to getLastKnownPositionAsync.

NameTypeDescription
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

Type representing the location object.

NameTypeDescription
coordsLocationObjectCoords

The coordinates of the position.

mocked
(optional)
booleanOnly 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

Type representing the location GPS related data.

NameTypeDescription
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

Type representing options argument in getCurrentPositionAsync.

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

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)
booleanOnly 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)
numberOnly for:
Android

Minimum time to wait between each update in milliseconds. Default value may depend on accuracy option.

LocationPermissionResponse

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

PermissionResponse extended by:


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

LocationProviderStatus

Represents the object containing details about location provider.

NameTypeDescription
backgroundModeEnabledboolean-
gpsAvailable
(optional)
booleanOnly 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)
booleanOnly 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)
booleanOnly for:
Android

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

LocationRegion

Type representing geofencing region object.

NameTypeDescription
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

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

NameTypeDescription
remove() => void

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

LocationTaskOptions

Type representing background location task options.

LocationOptions extended by:


NameTypeDescription
activityType
(optional)
ActivityTypeOnly for:
iOS

The type of user activity associated with the location updates.

Default: ActivityType.Other

See: See Apple docs for more details.

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)
booleanOnly 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)
booleanOnly for:
iOS 11+

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

Default: false

LocationTaskServiceOptions

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

PermissionDetailsLocationAndroid

NameTypeDescription
accuracy'fine' | 'coarse' | 'none'

Indicates the type of location provider.

scope'fine' | 'coarse' | 'none'

Deprecated. Use accuracy field instead.

PermissionDetailsLocationIOS

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

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

PermissionHookOptions

Literal Type: multiple types

Acceptable values are: PermissionHookBehavior | Options

Enums

Accuracy

Enum with available location accuracies.

Accuracy Values

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

Enum with available activity types of background location tracking.

ActivityType Values

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.

Only for:
iOS 12+

Airborne

ActivityType.Airborne = 5

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

GeofencingEventType

A type of the event that geofencing task can receive.

GeofencingEventType Values

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

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

GeofencingRegionState Values

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.

PermissionStatus

PermissionStatus Values

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.

权限

¥Permissions

安卓

¥Android

注意:Android 版 Expo Go 中不提供前台和后台服务。

¥Note: Foreground and background services are not available in Expo Go for Android.

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

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

  • ACCESS_COARSE_LOCATION:获取设备的大概位置

    ¥ACCESS_COARSE_LOCATION: for approximate device location

  • ACCESS_FINE_LOCATION:用于精确的设备定位

    ¥ACCESS_FINE_LOCATION: for precise device location

以下权限是可选的:

¥The following permissions are optional:

  • FOREGROUND_SERVICEFOREGROUND_SERVICE_LOCATION:能够在应用打开但处于后台状态时访问位置。仅从 Android 14 开始需要 FOREGROUND_SERVICE_LOCATION。当你在新版本中启用此功能时,你将需要 提交你的应用以供审核并请求访问使用前台服务的权限

    ¥FOREGROUND_SERVICE and FOREGROUND_SERVICE_LOCATION: to be able to access location while the app is open but backgrounded. FOREGROUND_SERVICE_LOCATION is only required as of Android 14. When you enable this in a new build, you will need to submit your app for review and request access to use the foreground service permission.

  • ACCESS_BACKGROUND_LOCATION:能够在应用处于后台或关闭时访问位置。当你在新版本中启用此功能时,你将需要 提交你的应用以供审核并请求访问权限以使用后台位置权限

    ¥ACCESS_BACKGROUND_LOCATION: to be able to access location while the app is backgrounded or closed. When you enable this in a new build, you will need to submit your app for review and request access to use the background location permission.

Android PermissionDescription

ACCESS_COARSE_LOCATION

Allows an app to access approximate location.

Alternatively, you might want ACCESS_FINE_LOCATION.

ACCESS_FINE_LOCATION

Allows an app to access precise location.

Alternatively, you might want ACCESS_COARSE_LOCATION.

FOREGROUND_SERVICE

Allows a regular application to use Service.startForeground.

Allows a regular application to use Service.startForeground.

FOREGROUND_SERVICE_LOCATION

Allows a regular application to use Service.startForeground with the type "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.

If you're requesting this permission, you must also request either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION. Requesting this permission by itself doesn't give you location access.

排除许可

¥Excluding a permission

注意:从应用中的模块中排除所需的权限可能会破坏与该权限相对应的功能。始终确保包含模块依赖的所有权限。

¥Note: Excluding a required permission from a module in your app can break the functionality corresponding to that permission. Always make sure to include all permissions a module is dependent on.

当你的 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 权限。要了解有关定位精度级别的更多信息,请参阅 安卓文档

¥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 系统

¥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.
Expo 中文网 - 粤ICP备13048890号