All Guides How to request for user location in Expo React Native

How to request for user location in Expo React Native

Some apps require user location and you can get the user permission by using expo-location, let's get started.


Install Expo Location and Update App Configuration

Start by installing the expo-location package.

npx expo install expo-location

For the app.json you will need to update the plugin section.

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

Implement Request Location

From any of your application screens add the following code to request user for location permission.

import * as Location from "expo-location";
import { useState, useEffect } from "react";

export default function Page() {
  const [hasPermission, setHasPermission] = useState<boolean>(false);

  useEffect(() => {
    const requestLocation = async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();

      if (status !== "granted") {
        setHasPermission(false);
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      console.log('Your current location is:', location);
    };
  }, [])
}

Refresh your application and you will see the location data in your console.

{
  "coords": {
    "accuracy": 5,
    "altitude": 0,
    "altitudeAccuracy": -1,
    "heading": -1,
    "latitude": 37.785834,
    "longitude": -122.406417,
    "speed": -1
  },
  "timestamp": 1728112922188.854
}

Enable Location on Simulator/Emulator

For the iOS simulator ensure that you set up the location from Features > Location while for the Android emulator it's accessible from the Settings > Location.

Introducing NeNews React Native UI Kit

HestiaKit Premium

You have to be signed in to favorite this screen

Share

HestiaKit Premium

This is HestiaKit premium component