Get location in React Native and Expo

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

Today I’m going to show you how to obtain location using React Native and Expo:

We’re going to use the library expo-location (https://docs.expo.dev/versions/latest/sdk/location/)

First, let’s install it:

expo install expo-location

This library automatically adds the necessary permissions to the Android Manifest (required to use location):

  • ACCESS_COARSE_LOCATION: for approximate device location
  • ACCESS_FINE_LOCATION: for precise device location
  • FOREGROUND_SERVICE: to subscribe to location updates while the app is in use

However, it doesn’t add the permission to use background location: ACCESS_BACKGROUND_LOCATION. If we want to add that permission, we’ll have to do it manually in app.js.

Now we import the library to use it in our code:

import * as Location from 'expo-location';

Once imported, we go to the render function and add the necessary methods to obtain the location.

const Component = ({ navigation }) => {

// State to store the obtained location
const [location, setLocation] = useState(null);

// Method to request location permissions and get location
 const getLocationPermission = async () => {
  
        let { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            alert('Permission to access location was denied');
            return;
        }

        let location = await Location.getCurrentPositionAsync({});
        setLocation(location);
        console.log('Location: ' + JSON.stringify(location) + " Latitude: " + location.coords.latitude + " Longitude: " + location.coords.longitude);
    };

 return (
        
            

Now let me explain the code.

First, we create a state to store the obtained location:

const [location, setLocation] = useState(null);

The method const getLocationPermission = async () => { is the one that allows us to obtain the location.

  • First, it requests location permission.
  • If permission is granted, it returns the location.

To get the coordinates, we use the parameters of the returned object:

location.coords.latitude

location.coords.longitude

Leave a Comment