16.5.5 • Published 2 days ago

expo-location v16.5.5

Weekly downloads
114,358
License
MIT
Repository
github
Last release
2 days ago

expo-location

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

Installation

If your app is running in Expo then everything is already set up for you, just import { Location } from 'expo';

Otherwise, you need to install the package from npm registry.

yarn add expo-location or npm install expo-location

Also, make sure that you have expo-core and expo-permissions installed, as they are required by expo-location to work properly.

iOS

Add the dependency to your Podfile:

pod 'EXLocation', path: '../node_modules/expo-location/ios'

and run pod install under the parent directory of your Podfile.

Android

  1. Append the following lines to android/settings.gradle:
    include ':expo-location'
    project(':expo-location').projectDir = new File(rootProject.projectDir, '../node_modules/expo-location/android')
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
    compile project(':expo-location')
  3. Add new LocationPackage() to your module registry provider in MainApplication.java.

Usage

You must request permission to access the user's location before attempting to get it. To do this, you will want to use the Permissions API. You can see this in practice in the following example.

import React, { Component } from 'react';
import { Platform, Text, View, StyleSheet } from 'react-native';
import { Location } from 'expo-location';
import { Permissions } from 'expo-permissions';

export default class App extends Component {
  state = {
    location: null,
    errorMessage: null,
  };

  componentDidMount() {
    this.getLocationAsync();
  }

  getLocationAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
      return;
    }

    const location = await Location.getCurrentPositionAsync({});
    this.setState({ location });
  };

  render() {
    let text = 'Waiting...';

    if (this.state.errorMessage) {
      text = this.state.errorMessage;
    } else if (this.state.location) {
      text = JSON.stringify(this.state.location);
    }

    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>{text}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 40,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    textAlign: 'center',
  },
});

Methods

Location.getCurrentPositionAsync(options)

Get the current position of the device.

Arguments

  • options (object) --

    A map of options:

    • enableHighAccuracy (boolean) -- Whether to enable high-accuracy mode. For low-accuracy the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).
    • maximumAge (number) -- (Android only). If specified, allow returning a previously cached position that is at most this old in milliseconds. If not specified, always gets a new location. On iOS this option is ignored and a new location is always returned.
    • timeout (number) -- (Android only). If specified, allow device to determine the position for a maximum of limit time (in miliseconds).

Returns

Returns a promise resolving to an object with the following fields:

  • coords (object) -- The coordinates of the position, with the following fields:
    • latitude (number) -- The latitude in degrees.
    • longitude (number) -- The longitude in degrees.
    • altitude (number) -- The altitude in meters above the WGS 84 reference ellipsoid.
    • accuracy (number) -- The radius of uncertainty for the location, measured in meters.
    • altitudeAccuracy (number) -- The accuracy of the altitude value, in meters (iOS only).
    • heading (number) -- 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.
    • speed (number) -- The instantaneous speed of the device in meters per second.
  • timestamp (number) -- The time at which this position information was obtained, in milliseconds since epoch.

Location.watchPositionAsync(options, callback)

Subscribe to location updates from the device. Please note that updates will only occur while the application is in the foreground. Background location tracking is planned, but not yet implemented.

Arguments

  • options (object) --

    A map of options:

    • enableHighAccuracy (boolean) -- Whether to enable high accuracy mode. For low accuracy the implementation can avoid geolocation providers that consume a significant amount of power (such as GPS).
    • timeInterval (number) -- Minimum time to wait between each update in milliseconds.
    • distanceInterval (number) -- Receive updates only when the location has changed by at least this distance in meters.
  • callback (function) --

    This function is called on each location update. It is passed exactly one parameter: an object with the following fields:

    • coords (object) -- The coordinates of the position, with the following fields:
      • latitude (number) -- The latitude in degrees.
      • longitude (number) -- The longitude in degrees.
      • altitude (number) -- The altitude in meters above the WGS 84 reference ellipsoid.
      • accuracy (number) -- The radius of uncertainty for the location, measured in meters.
      • altitudeAccuracy (number) -- The accuracy of the altitude value, in meters (iOS only).
      • heading (number) -- 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.
      • speed (number) -- The instantaneous speed of the device in meters per second.
    • timestamp (number) -- The time at which this position information was obtained, in milliseconds since epoch.

Returns

Returns a promise resolving to a subscription object, which has one field:

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

Location.getProviderStatusAsync()

Check status of location providers.

Returns

Returns a promise resolving to an object with the following fields:

  • locationServicesEnabled (boolean) -- Whether location services are enabled.
  • gpsAvailable (boolean) (android only) -- If the GPS provider is available, if yes, location data will be from GPS.
  • networkAvailable (boolean) (android only) -- If the network provider is available, if yes, location data will be from cellular network.
  • passiveAvailable (boolean) (android only) -- If the passive provider is available, if yes, location data will be determined passively.

Location.getHeadingAsync()

Gets the current heading information from the device

Returns

Object with:

  • magHeading (number) — measure of magnetic north in degrees
  • trueHeading (number) — measure of true north in degrees (needs location permissions, will return -1 if not given)
  • accuracy (number) — level of callibration 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

Location.watchHeadingAsync(callback)

Suscribe to compass updates from the device

Arguments

  • callback (function) --

    This function is called on each compass update. It is passed exactly one parameter: an object with the following fields:

    • magHeading (number) — measure of magnetic north in degrees
    • trueHeading (number) — measure of true north in degrees (needs location permissions, will return -1 if not given)
    • accuracy (number) — level of callibration 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

Returns

Returns a promise resolving to a subscription object, which has one field:

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

Location.geocodeAsync(address)

Geocode an address string to latitiude-longitude location.

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.

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

Arguments

  • address (string) -- A string representing address, eg. "Baker Street London"

Returns

Returns a promise resolving to an array (in most cases its size is 1) of geocoded location objects with the following fields:

  • latitude (number) -- The latitude in degrees.
  • longitude (number) -- The longitude in degrees.
  • altitude (number) -- The altitude in meters above the WGS 84 reference ellipsoid.
  • accuracy (number) -- The radius of uncertainty for the location, measured in meters.

Location.reverseGeocodeAsync(location)

Reverse geocode a location to postal address.

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.

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

Arguments

  • location (object) -- An object representing a location:

    • latitude (number) -- The latitude of location to reverse geocode, in degrees.
    • longitude (number) -- The longitude of location to reverse geocode, in degrees.

Returns

Returns a promise resolving to an array (in most cases its size is 1) of address objects with following fields:

  • city (string) -- City name of the address.
  • street (string) -- Street name of the address.
  • region (string) -- Region/area name of the address.
  • postalCode (string) -- Postal code of the address.
  • country (string) -- Localized country name of the address.
  • name (string) -- Place name of the address, for example, "Tower Bridge".

Location.setApiKey(apiKey)

Sets a Google API Key for using Geocoding API. This method can be useful for Android devices that do not have Google Play Services, hence no Geocoder Service. After setting the key using Google's API will be possible.

Arguments

  • apiKey (string) -- API key collected from Google Developer site.
consultadigitalblindajevenue-modern-pdf-reader-offlineraodaor-appraodaor-app-poetryraodaor-app1@clockbook-app/timetracker-module-mobilereact-native-slider-kfreact-native-code-push-expo-plugin-managed-workflow@everything-registry/sub-chunk-1630@otesbylhe/reusablecomponentssales-sync-mobileconsulta-digital@cuongweallnet/rn-gifted-chatmairiesimplonsharedtextshot-on-targetsosappstickersmashdp-taro-taro-rnmaro-rnunitx-uieasy-expomuba-mapmuba-popup-permissionsuser-localization-settings@giasin/react-native-web-mapsmoor-react-native-componentskmandinibbnksdk@andreciornavei/rn-essentialscom.loggi.teste.toolbox@colorfulwindmill/five-films-serviceblueko@cognativ/locationtrack_tk02nearestdevs-apptrv-exporeact-native-ali-smartlivingreact-native-chatwhatreact-native-extended-gifted-chatreact-native-json-formsreact-native-form-builder2@mifind/taro-rn@life-health-emergency/lhe-reusable-rn-uizero-degreezeninvest@rvis/rvis-rn-templateexpo-torqexpo-mapbox-navigation@hammadj/react-native-gifted-chatfoozard-mobile-componentswrapped-native@kfox/exporeact-native-qibla-compass@staxy-app/react-native-web-mapsreact-native-web-locationreact-native-template-gaussreact-native-template-gaussfleettemplate@sreuter/react-native-web-maps@hubspire/expo-apppcmli.umbrella.react-native@infinitebrahmanuniverse/nolb-expo@rtarojs/taro-rnzippi-market-corepikop-apppolse@kafudev/react-native-core@admin-layout/timetracker-module-mobileridecabrider@vnxjs/vnmf-rnrn-location-hookrnshell@agreejs/taro-rn@teovilla/react-native-web-maps@wq/expo-templaterecytrack@tarojs/taro-rn
17.0.1

2 days ago

17.0.0

6 days ago

16.5.5

2 months ago

16.5.4

2 months ago

16.5.3

3 months ago

16.5.2

4 months ago

16.5.1

4 months ago

16.5.0

5 months ago

16.4.0

6 months ago

16.3.0

8 months ago

16.1.0

10 months ago

16.2.0

9 months ago

16.0.0

10 months ago

16.2.1

9 months ago

15.3.0

11 months ago

15.2.0

12 months ago

15.1.1

1 year ago

15.1.0

1 year ago

15.0.0

2 years ago

15.0.1

1 year ago

14.3.0

2 years ago

14.2.0

2 years ago

14.2.1

2 years ago

14.2.2

2 years ago

14.1.0

2 years ago

14.0.0

2 years ago

14.0.1

2 years ago

14.0.2

2 years ago

13.0.4

3 years ago

13.0.2

3 years ago

13.0.3

3 years ago

13.0.1

3 years ago

13.0.0

3 years ago

12.1.3

3 years ago

12.1.2

3 years ago

12.1.1

3 years ago

12.1.0

3 years ago

12.0.4

3 years ago

12.0.3

3 years ago

12.0.2

3 years ago

12.0.1

3 years ago

12.0.0

3 years ago

11.0.0

3 years ago

10.0.0

3 years ago

9.0.1

4 years ago

9.0.0

4 years ago

8.3.0

4 years ago

8.2.1

4 years ago

8.2.0

4 years ago

8.1.0

4 years ago

8.0.0

4 years ago

7.0.0

5 years ago

7.0.0-rc.0

5 years ago

6.0.0

5 years ago

6.0.0-rc.0

5 years ago

5.0.1

5 years ago

5.0.0

5 years ago

5.0.0-rc.0

5 years ago

4.0.0

5 years ago

3.0.0

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

2.0.0-rc.3

5 years ago

2.0.0-rc.2

5 years ago

2.0.0-rc.1

5 years ago

2.0.0-rc.0

5 years ago

1.1.0

5 years ago

1.1.0-rc.1

5 years ago

1.1.0-rc.0

6 years ago

1.0.0

6 years ago

1.0.0-rc.0

6 years ago