Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
expo install expo-location
expo install expo-location
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import * as Location from 'expo-location';
import * as Location from 'expo-location';
import * as Location from 'expo-location';

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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 (
<view style="{styles.container}">
<button title="Get Location" onpress="{getLocationPermission}">
)
};
export default Component;</button></view>
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 ( <view style="{styles.container}"> <button title="Get Location" onpress="{getLocationPermission}"> ) }; export default Component;</button></view>
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);
const [location, setLocation] = useState(null);

The method

const getLocationPermission = async () => {
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

0

Leave a Comment