Location services help your app find where the user is on the map. This lets your app show nearby places or give directions.
Location services in 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.
Geolocation.getCurrentPosition(position => console.log(position.coords));
const watchId = Geolocation.watchPosition(position => setLocation(position.coords));
Geolocation.clearWatch(watchId);
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.
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' } });
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.
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.
Practice
Geolocation.getCurrentPosition in a React Native app?Solution
Step 1: Understand the function purpose
Geolocation.getCurrentPositionis designed to get the user's location only once when called.Step 2: Differentiate from continuous tracking
Continuous tracking useswatchPosition, notgetCurrentPosition.Final Answer:
To get the user's current location once -> Option DQuick Check:
Single location fetch = getCurrentPosition [OK]
- Confusing getCurrentPosition with watchPosition
- Thinking it requests permissions automatically
- Assuming it tracks location continuously
Solution
Step 1: Identify correct API usage
The correct React Native API call for one-time location isGeolocation.getCurrentPositionwith success and error callbacks.Step 2: Eliminate incorrect options
watchPositionis for continuous tracking,navigator.locationandLocation.getPositionare not valid React Native APIs.Final Answer:
Geolocation.getCurrentPosition(successCallback, errorCallback); -> Option CQuick Check:
Correct method and parameters = Geolocation.getCurrentPosition(successCallback, errorCallback); [OK]
- Using watchPosition for one-time location
- Using browser navigator API in React Native
- Incorrect method names or missing callbacks
Geolocation.getCurrentPosition( position => console.log(position.coords.latitude), error => console.log(error.message) );
Solution
Step 1: Analyze success callback
The success callback logsposition.coords.latitude, which is a number representing latitude.Step 2: Understand error callback usage
The error callback logs error messages only if permission is denied or fetching fails, which is not the case here.Final Answer:
Logs the user's latitude coordinate as a number -> Option AQuick Check:
Success callback logs latitude number [OK]
- Expecting entire position object logged
- Confusing error callback with success callback
- Assuming syntax error due to arrow functions
const watchId = Geolocation.watchPosition( position => console.log(position.coords.longitude), error => console.log(error.message) ); Geolocation.clearWatch(watchId);
Solution
Step 1: Understand watchPosition behavior
watchPositionstarts tracking and returns a watchId to stop it later.Step 2: Analyze clearWatch usage
CallingclearWatch(watchId)immediately after starting tracking stops it right away, so no updates will be received.Final Answer:
clearWatch is called immediately, stopping tracking instantly -> Option BQuick Check:
Immediate clearWatch stops tracking [OK]
- Calling clearWatch too soon
- Mixing argument order in watchPosition
- Assuming watchPosition returns nothing
Solution
Step 1: Understand continuous tracking with filtering
watchPositionsupports options likedistanceFilterto update only when user moves a set distance, saving resources.Step 2: Compare other options
UsinggetCurrentPositionrepeatedly wastes battery and CPU. Filtering manually after every update is less efficient. Requesting location once won't track movement.Final Answer:
UsewatchPositionwithdistanceFilter: 50option to limit updates -> Option AQuick Check:
distanceFilter option limits updates efficiently [OK]
- Polling location repeatedly with getCurrentPosition
- Ignoring distanceFilter and filtering manually
- Requesting location only once for continuous tracking
Ready to prove it?
Pass the test and this pattern moves unknown
