Paramclasses Academy - Blog

Tutorials Details

←
Post 27 of 39
→

How to setup Using GPS and Location Services in React Native

How to setup Using GPS and Location Services in React Native

November 5, 2026

1. Introduction

GPS and location services allow a mobile application to identify the geographical position of a device. React Native developers can use this functionality to build location-based applications.

Examples include:

  • Food delivery applications.

  • Ride-booking applications.

  • Navigation applications.

  • Weather applications.

  • Fitness and activity tracking applications.

  • Nearby shop and service finder applications.

In this tutorial, we will use the Expo Location package to access the device's location.

By the end of this tutorial, we will build a complete My Location App that can:

  1. Request location permission.

  2. Check whether location services are enabled.

  3. Get the device's current GPS coordinates.

  4. Display latitude and longitude.

  5. Display location accuracy.

  6. Convert coordinates into a readable address using reverse geocoding.

  7. Refresh the current location.

2. What Is GPS?

GPS stands for Global Positioning System. It is a satellite-based navigation system that helps devices determine their geographical position.

A GPS-enabled device can provide information such as:

  • Latitude: Position north or south of the Equator.

  • Longitude: Position east or west of the Prime Meridian.

  • Accuracy: Estimated precision of the reported position.

  • Altitude: Approximate height above sea level, when available.

  • Heading: Direction of movement, when available.

For example:

{
  latitude: 21.2514,
  longitude: 81.6296,
  accuracy: 10
}

These values are illustrative coordinates, not the user's actual location.

3. What Is Expo Location?

Expo Location is a library that allows React Native applications to access device location information.

It provides APIs for:

  • Requesting foreground location permissions.

  • Getting the current device location.

  • Getting the last known location.

  • Listening for location updates.

  • Reverse geocoding coordinates into an address.

  • Checking location service availability.

We will use the expo-location package.

Official documentation:

https://docs.expo.dev/versions/latest/sdk/location/

4. Understanding Location Permissions

An application cannot access a user's location without the appropriate permission.

There are two important types of location access.

Foreground Location

Foreground location allows the application to access location while the application is being used.

Examples:

  • Displaying the current location.

  • Finding nearby restaurants.

  • Showing a user's position on a map.

Background Location

Background location allows an application to receive location updates even when it is not actively displayed.

Examples:

  • Fitness tracking.

  • Delivery tracking.

  • Certain navigation applications.

Background location requires additional platform configuration, permissions, and testing. It is outside the scope of our beginner project.

In this tutorial, we will request foreground location permission only.

5. Create a New React Native Project

Open your terminal and run:

npx create-expo-app@latest MyLocationApp --template blank

Move into the project folder:

cd MyLocationApp

Open the project in Visual Studio Code:

code .

6. Install Expo Location

Run the following command:

npx expo install expo-location

Expo will install a version compatible with your project's Expo SDK.

Verify that the package appears in your package.json dependencies.

7. Understand the Project Structure

Our project will use the following structure:

MyLocationApp/
│
├── assets/
│
├── node_modules/
│
├── App.js
│
├── app.json
│
├── package.json
│
└── ...

We will write our application code inside App.js.

8. Understand Important Location Methods

Before building the application, understand these methods.

8.1 Request Foreground Permission

const permission =
  await Location.requestForegroundPermissionsAsync();

This requests permission to access location while the application is in use.

8.2 Check Location Services

const enabled =
  await Location.hasServicesEnabledAsync();

This checks whether the device's location services are enabled.

8.3 Get Current Location

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

This requests a current location fix.

8.4 Get Latitude and Longitude

const latitude = location.coords.latitude;
const longitude = location.coords.longitude;

8.5 Get Location Accuracy

const accuracy = location.coords.accuracy;

Accuracy is an estimated horizontal precision in metres. A smaller number generally indicates a more precise estimate.

8.6 Reverse Geocoding

const address = await Location.reverseGeocodeAsync({
  latitude,
  longitude,
});

Reverse geocoding converts geographical coordinates into address information.

The returned address may contain:

  • Street.

  • City.

  • District.

  • Region.

  • Postal code.

  • Country.

Address information depends on the device's available geocoding service and may not always be complete.

9. Build the My Location App

Now we will create the complete application.

Open App.js and replace its existing code with the following.

Complete App.js Code

import React, { useState } from 'react';

import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  ScrollView,
  Alert,
} from 'react-native';

import * as Location from 'expo-location';

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

  const [address, setAddress] = useState(null);

  const [loading, setLoading] = useState(false);

  const [error, setError] = useState('');

  const getCurrentLocation = async () => {
    try {
      setLoading(true);

      setError('');

      setLocation(null);

      setAddress(null);

      // Step 1: Check location services

      const servicesEnabled =
        await Location.hasServicesEnabledAsync();

      if (!servicesEnabled) {
        setError(
          'Please enable location services on your device.'
        );

        Alert.alert(
          'Location Disabled',
          'Please turn on GPS or location services.'
        );

        return;
      }

      // Step 2: Request foreground permission

      const permission =
        await Location.requestForegroundPermissionsAsync();

      if (permission.status !== 'granted') {
        setError(
          'Location permission was not granted.'
        );

        Alert.alert(
          'Permission Required',
          'Please allow location access to continue.'
        );

        return;
      }

      // Step 3: Get current location

      const currentLocation =
        await Location.getCurrentPositionAsync({
          accuracy: Location.Accuracy.Balanced,
        });

      setLocation(currentLocation);

      // Step 4: Extract coordinates

      const latitude =
        currentLocation.coords.latitude;

      const longitude =
        currentLocation.coords.longitude;

      // Step 5: Convert coordinates into address

      try {
        const addressResult =
          await Location.reverseGeocodeAsync({
            latitude,
            longitude,
          });

        if (addressResult.length > 0) {
          setAddress(addressResult[0]);
        } else {
          setAddress(null);
        }
      } catch (geocodeError) {
        console.log(
          'Reverse geocoding error:',
          geocodeError
        );

        setAddress(null);
      }

    } catch (error) {
      console.log('Location error:', error);

      setError(
        'Unable to get location. Please try again.'
      );

    } finally {
      setLoading(false);
    }
  };

  const getFullAddress = () => {
    if (!address) {
      return 'Address information is unavailable.';
    }

    const parts = [
      address.name,
      address.street,
      address.district,
      address.city,
      address.region,
      address.postalCode,
      address.country,
    ];

    return [
      ...new Set(
        parts.filter(
          (part) => part && part.trim()
        )
      ),
    ].join(', ');
  };

  return (
    <ScrollView
      contentContainerStyle={styles.container}
    >

      <Text style={styles.title}>
        My Location App
      </Text>

      <Text style={styles.subtitle}>
        React Native GPS Location Tutorial
      </Text>

      <View style={styles.locationIcon}>
        <Text style={styles.iconText}>
          GPS
        </Text>
      </View>

      <TouchableOpacity
        style={styles.button}
        onPress={getCurrentLocation}
        disabled={loading}
      >
        <Text style={styles.buttonText}>
          {loading
            ? 'Getting Location...'
            : 'Get My Current Location'}
        </Text>
      </TouchableOpacity>

      {loading && (
        <ActivityIndicator
          size="large"
          color="#2563eb"
          style={styles.loader}
        />
      )}

      {error !== '' && (
        <Text style={styles.error}>
          {error}
        </Text>
      )}

      {location && (
        <View style={styles.card}>

          <Text style={styles.cardTitle}>
            Location Details
          </Text>

          <View style={styles.infoBox}>
            <Text style={styles.label}>
              Latitude
            </Text>

            <Text style={styles.value}>
              {location.coords.latitude.toFixed(6)}
            </Text>
          </View>

          <View style={styles.infoBox}>
            <Text style={styles.label}>
              Longitude
            </Text>

            <Text style={styles.value}>
              {location.coords.longitude.toFixed(6)}
            </Text>
          </View>

          <View style={styles.infoBox}>
            <Text style={styles.label}>
              Accuracy
            </Text>

            <Text style={styles.value}>
              {location.coords.accuracy !== null
                ? `${location.coords.accuracy.toFixed(2)} metres`
                : 'Not available'}
            </Text>
          </View>

          <View style={styles.infoBox}>
            <Text style={styles.label}>
              Altitude
            </Text>

            <Text style={styles.value}>
              {location.coords.altitude !== null
                ? `${location.coords.altitude.toFixed(2)} metres`
                : 'Not available'}
            </Text>
          </View>

          <View style={styles.infoBox}>
            <Text style={styles.label}>
              Address
            </Text>

            <Text style={styles.address}>
              {getFullAddress()}
            </Text>
          </View>

          <Text style={styles.timestamp}>
            Location timestamp: {'\n'}
            {new Date(
              location.timestamp
            ).toLocaleString()}
          </Text>

        </View>
      )}

      <Text style={styles.footer}>
        Your location is accessed only after
        you grant permission.
      </Text>

    </ScrollView>
  );
}

const styles = StyleSheet.create({

  container: {
    flexGrow: 1,
    backgroundColor: '#f1f5f9',
    alignItems: 'center',
    padding: 20,
    paddingTop: 60,
  },

  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#0f172a',
  },

  subtitle: {
    fontSize: 14,
    color: '#64748b',
    marginTop: 8,
    textAlign: 'center',
  },

  locationIcon: {
    width: 110,
    height: 110,
    borderRadius: 55,
    backgroundColor: '#dbeafe',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 30,
  },

  iconText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#2563eb',
  },

  button: {
    backgroundColor: '#2563eb',
    padding: 16,
    borderRadius: 12,
    width: '100%',
    alignItems: 'center',
  },

  buttonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },

  loader: {
    marginTop: 20,
  },

  error: {
    color: '#dc2626',
    marginTop: 20,
    textAlign: 'center',
  },

  card: {
    width: '100%',
    backgroundColor: '#ffffff',
    padding: 18,
    borderRadius: 15,
    marginTop: 25,
    elevation: 3,
  },

  cardTitle: {
    fontSize: 21,
    fontWeight: 'bold',
    color: '#0f172a',
    marginBottom: 15,
  },

  infoBox: {
    backgroundColor: '#f8fafc',
    padding: 13,
    borderRadius: 9,
    marginBottom: 12,
  },

  label: {
    fontSize: 13,
    color: '#64748b',
    marginBottom: 5,
  },

  value: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#1e293b',
  },

  address: {
    fontSize: 15,
    color: '#1e293b',
    lineHeight: 23,
  },

  timestamp: {
    fontSize: 12,
    color: '#64748b',
    marginTop: 10,
  },

  footer: {
    fontSize: 12,
    color: '#64748b',
    textAlign: 'center',
    marginTop: 25,
    marginBottom: 20,
  },

});

10. Understand the Application Code

Let's understand how the application works.

Step 1: Import Expo Location

import * as Location from 'expo-location';

This imports the Expo Location library.

We use its methods to request permissions and access GPS information.

Step 2: Create State Variables

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

const [address, setAddress] = useState(null);

const [loading, setLoading] = useState(false);

const [error, setError] = useState('');

These state variables manage:

  • location: Stores GPS information.

  • address: Stores reverse-geocoded address.

  • loading: Controls the loading indicator.

  • error: Stores error messages.

Step 3: Check GPS Availability

const servicesEnabled =
  await Location.hasServicesEnabledAsync();

This checks whether location services are enabled on the device.

If GPS or location services are disabled, the application displays an appropriate message.

Step 4: Request Permission

const permission =
  await Location.requestForegroundPermissionsAsync();

The operating system displays a permission dialog.

If permission is denied, the application does not attempt to access the current location.

Step 5: Get GPS Coordinates

const currentLocation =
  await Location.getCurrentPositionAsync({
    accuracy: Location.Accuracy.Balanced,
  });

This requests the device's current position.

We use balanced accuracy to avoid unnecessarily demanding the highest accuracy for this basic example.

Step 6: Extract Coordinates

const latitude =
  currentLocation.coords.latitude;

const longitude =
  currentLocation.coords.longitude;

Latitude and longitude identify the geographical position.

Step 7: Convert Coordinates Into an Address

const addressResult =
  await Location.reverseGeocodeAsync({
    latitude,
    longitude,
  });

This converts geographical coordinates into readable address information.

Reverse geocoding is a separate operation and can fail even when GPS coordinates are available.

Step 8: Display Location Information

We use React state to display the coordinates, accuracy, altitude and address on the screen.

When the state changes, React Native updates the interface.

11. Run the Application

Start the Expo development server:

npx expo start

You can test the application using:

  • Expo Go on a compatible physical device.

  • An Android Emulator.

  • An iOS Simulator.

For the best real-world GPS testing, use a physical device with location services enabled.

12. Test the Application Step by Step

Follow these steps:

  1. Open the My Location App.

  2. Press Get My Current Location.

  3. Allow location access when the permission dialog appears.

  4. Wait for the GPS location to load.

  5. Check the latitude and longitude.

  6. Check the estimated accuracy.

  7. Check the address information.

  8. Press the button again to refresh the location.

Your actual coordinates and address will depend on the device's physical location and available location services.

13. Test Location in Android Emulator

If you are using Android Studio:

  1. Open Android Studio.

  2. Start your Android Emulator.

  3. Open the emulator's Settings.

  4. Navigate to Location.

  5. Enable location services.

  6. Open the Extended Controls panel in the emulator.

  7. Select the Location section.

  8. Set a simulated location.

  9. Run your application again.

If the emulator does not return a location, verify its simulated location settings.

Expo's official documentation explains emulator location configuration:

https://docs.expo.dev/versions/latest/sdk/location/

14. Common Errors and Solutions

Error 1: Location Permission Denied

Reason: The user rejected the location permission request.

Solution: Explain why the permission is needed and allow the user to grant it through the device settings.

Do not repeatedly request permission without explaining the feature.

Error 2: Location Services Disabled

Reason: GPS or device location services are switched off.

Solution: Enable location services from the device settings.

Error 3: Unable to Get Current Location

Possible reasons:

  • GPS signal is weak.

  • The device is indoors.

  • Emulator location is not configured.

  • Location services are disabled.

  • The location request takes longer than expected.

Solution: Test outdoors, verify emulator settings and retry.

Error 4: Address Is Not Displayed

Reason: Reverse geocoding may return an empty result or fail.

Solution: Check that the coordinates were obtained successfully. The app should still display latitude and longitude even if address lookup fails.

Error 5: Permission Dialog Does Not Appear Again

Reason: The user may have previously denied permission, or the operating system may have restricted another request.

Solution: Check application permissions in device settings. During development, reinstalling the app can help reset the permission test state.

15. Foreground Location vs Background Location

Feature Foreground Location Background Location
App is open Yes Yes
App is minimized Generally no continuous tracking Can be supported
Permission complexity Lower Higher
Battery consumption Usually lower Can be higher
Beginner project Recommended Advanced

For production applications, request only the location access required by the feature.

Background tracking also requires additional configuration and platform-specific restrictions. Do not assume that foreground permission automatically enables background tracking.

16. Location Privacy and Security Best Practices

Location data is sensitive user information.

Follow these practices:

  1. Explain why the application needs location access.

  2. Request permission only when the feature requires it.

  3. Prefer foreground location when continuous background access is unnecessary.

  4. Do not expose a user's coordinates publicly without consent.

  5. Avoid storing precise location information unnecessarily.

  6. Use HTTPS when sending location data to a backend.

  7. Protect location information using appropriate authentication and authorization.

  8. Provide a clear way to stop location tracking if tracking is implemented.

17. Practical Exercise

Try extending the My Location App with these features:

Exercise 1: Add a button to display only latitude and longitude.

Exercise 2: Add a separate button to refresh the current address.

Exercise 3: Display the location accuracy in metres.

Exercise 4: Show an alert when location permission is denied.

Exercise 5: Add a feature to open the current coordinates in a map application.

These exercises will help you understand how location services work in real mobile applications.

18. Frequently Asked Questions

Q1. Which package is used for GPS in Expo React Native?

We use expo-location to access device location information.

Q2. Is location permission required?

Yes. The operating system requires the appropriate permission before an application can access protected location information.

Q3. What is latitude?

Latitude represents a position north or south of the Equator.

Q4. What is longitude?

Longitude represents a position east or west of the Prime Meridian.

Q5. What is reverse geocoding?

Reverse geocoding converts geographical coordinates into readable address information.

Q6. Can we get the current location without GPS?

Devices can use different location sources, including GPS, Wi-Fi and cellular networks. The available accuracy depends on the device and environment.

Q7. Can React Native track location in the background?

Yes, with additional background permissions, native configuration and platform-specific requirements. This tutorial covers foreground location only.

Q8. Does Expo Location work with Expo Go?

Yes. The Expo Location library is included in Expo Go. Production builds may require native permission configuration.

19. Conclusion

In this tutorial, we learned how to use GPS and location services in React Native with Expo Location.

We covered:

  • Installing Expo Location.

  • Requesting foreground location permission.

  • Checking device location services.

  • Getting current GPS coordinates.

  • Displaying latitude and longitude.

  • Understanding location accuracy.

  • Performing reverse geocoding.

  • Handling errors and permission restrictions.

  • Testing GPS functionality in an Android Emulator.

We also built a practical My Location App that can retrieve and display the current device location.

GPS and location services are important features for building modern mobile applications such as delivery apps, navigation apps, fitness apps and location-based services.

←
Post 27 of 39
→