0
0
React Nativemobile~5 mins

Location services in React Native

Choose your learning style9 modes available
Introduction

Location services help your app find where the user is on the map. This lets your app show nearby places or give directions.

Showing the user's current position on a map in a travel app.
Finding nearby restaurants or stores in a shopping app.
Tracking a delivery or ride in real time.
Checking in to a location in a social app.
Providing location-based reminders or alerts.
Syntax
React Native
import { useEffect, useState } from 'react';
import { View, Text, Button } from 'react-native';
import Geolocation from '@react-native-community/geolocation';

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

  const getLocation = () => {
    Geolocation.getCurrentPosition(
      position => setLocation(position.coords),
      error => console.log(error),
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  };

  useEffect(() => {
    getLocation();
  }, []);

  return (
    <View>
      <Text>Latitude: {location?.latitude}</Text>
      <Text>Longitude: {location?.longitude}</Text>
      <Button title="Refresh Location" onPress={getLocation} />
    </View>
  );
}

Use Geolocation.getCurrentPosition to get the user's current location once.

Remember to ask for location permission in your app settings or manifest.

Examples
Get the current location and print latitude and longitude to the console.
React Native
Geolocation.getCurrentPosition(position => console.log(position.coords));
Continuously watch the user's location and update state when it changes.
React Native
const watchId = Geolocation.watchPosition(position => setLocation(position.coords));
Stop watching the location updates using the watch ID.
React Native
Geolocation.clearWatch(watchId);
Sample App

This app shows the user's current latitude and longitude on the screen. It asks for location once when the app loads and also lets the user refresh the location by pressing a button. If there is an error getting the location, it shows the error message in red.

The UI is simple and accessible with clear labels and good contrast.

React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import Geolocation from '@react-native-community/geolocation';

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

  const getLocation = () => {
    Geolocation.getCurrentPosition(
      position => {
        setLocation(position.coords);
        setErrorMsg(null);
      },
      error => {
        setErrorMsg(error.message);
        setLocation(null);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  };

  useEffect(() => {
    getLocation();
  }, []);

  return (
    <View style={styles.container} accessible={true} accessibilityLabel="Location information">
      <Text style={styles.title}>Your Current Location</Text>
      {location ? (
        <>
          <Text style={styles.text}>Latitude: {location.latitude}</Text>
          <Text style={styles.text}>Longitude: {location.longitude}</Text>
        </>
      ) : errorMsg ? (
        <Text style={styles.error}>Error: {errorMsg}</Text>
      ) : (
        <Text style={styles.text}>Getting location...</Text>
      )}
      <Button title="Refresh Location" onPress={getLocation} accessibilityLabel="Refresh your current location" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#f0f8ff'
  },
  title: {
    fontSize: 24,
    marginBottom: 20,
    fontWeight: 'bold'
  },
  text: {
    fontSize: 18,
    marginBottom: 10
  },
  error: {
    fontSize: 18,
    marginBottom: 10,
    color: 'red'
  }
});
OutputSuccess
Important Notes

Always request permission to access location on both Android and iOS.

High accuracy mode uses GPS and may drain battery faster.

Test location features on a real device, as simulators may not provide real location data.

Summary

Location services let your app find where the user is.

Use Geolocation.getCurrentPosition to get location once, or watchPosition to track changes.

Always handle permissions and possible errors gracefully.