Bird
Raised Fist0
React Nativemobile~20 mins

Location services in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: LocationScreen
This screen shows the user's current location coordinates (latitude and longitude) using device location services.
Target UI
-------------------------
|      LocationScreen    |
|-----------------------|
|                       |
|  Latitude:             |
|  Longitude:            |
|                       |
|  [Get Current Location]|
-------------------------
Display latitude and longitude as text on the screen.
Add a button labeled 'Get Current Location'.
When the button is pressed, request location permission and fetch current location.
Update the displayed latitude and longitude with the fetched values.
Handle permission denial gracefully by showing an alert.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, Alert, StyleSheet } from 'react-native';

export default function LocationScreen() {
  const [location, setLocation] = useState({ latitude: null, longitude: null });

  const getLocation = () => {
    // TODO: Implement location fetching here
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Latitude: {location.latitude ?? 'Unknown'}</Text>
      <Text style={styles.label}>Longitude: {location.longitude ?? 'Unknown'}</Text>
      <Button title="Get Current Location" onPress={getLocation} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  label: {
    fontSize: 18,
    marginBottom: 12
  }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState } from 'react';
import { View, Text, Button, Alert, StyleSheet, Platform, PermissionsAndroid } from 'react-native';
import Geolocation from '@react-native-community/geolocation';

export default function LocationScreen() {
  const [location, setLocation] = useState({ latitude: null, longitude: null });

  const requestLocationPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
        );
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        Alert.alert('Permission error', 'Failed to request location permission');
        return false;
      }
    } else {
      return true; // iOS permission handled by Geolocation API
    }
  };

  const getLocation = async () => {
    const hasPermission = await requestLocationPermission();
    if (!hasPermission) {
      Alert.alert('Permission denied', 'Location permission is required to get current location.');
      return;
    }

    Geolocation.getCurrentPosition(
      position => {
        const { latitude, longitude } = position.coords;
        setLocation({ latitude, longitude });
      },
      error => {
        Alert.alert('Error', 'Could not get location: ' + error.message);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Latitude: {location.latitude ?? 'Unknown'}</Text>
      <Text style={styles.label}>Longitude: {location.longitude ?? 'Unknown'}</Text>
      <Button title="Get Current Location" onPress={getLocation} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  label: {
    fontSize: 18,
    marginBottom: 12
  }
});

This solution uses the @react-native-community/geolocation library to access the device's location. On Android, it requests location permission explicitly using PermissionsAndroid. On iOS, permission is handled automatically by the Geolocation API.

When the user taps the button, the app checks permission and then fetches the current location with high accuracy. The latitude and longitude are saved in state and displayed on screen. If permission is denied or an error occurs, an alert informs the user.

This approach ensures a friendly user experience and follows platform guidelines for location access.

Final Result
Completed Screen
-------------------------
|      LocationScreen    |
|-----------------------|
|                       |
|  Latitude: 37.4219983  |
|  Longitude: -122.084   |
|                       |
|  [Get Current Location]|
-------------------------
User taps 'Get Current Location' button.
App asks for location permission if not granted.
If permission granted, app fetches current location and updates latitude and longitude on screen.
If permission denied, an alert shows explaining permission is needed.
Stretch Goal
Add a loading indicator that shows while the app is fetching the location.
💡 Hint
Use a state variable to track loading status and conditionally render an ActivityIndicator component from react-native.

Practice

(1/5)
1. What is the main purpose of using Geolocation.getCurrentPosition in a React Native app?
easy
A. To display a map on the screen
B. To continuously track the user's location
C. To request permission for location access
D. To get the user's current location once

Solution

  1. Step 1: Understand the function purpose

    Geolocation.getCurrentPosition is designed to get the user's location only once when called.
  2. Step 2: Differentiate from continuous tracking

    Continuous tracking uses watchPosition, not getCurrentPosition.
  3. Final Answer:

    To get the user's current location once -> Option D
  4. Quick Check:

    Single location fetch = getCurrentPosition [OK]
Hint: Get current location once with getCurrentPosition [OK]
Common Mistakes:
  • Confusing getCurrentPosition with watchPosition
  • Thinking it requests permissions automatically
  • Assuming it tracks location continuously
2. Which of the following is the correct syntax to request the user's current location in React Native?
easy
A. navigator.location.getCurrentPosition(successCallback);
B. Geolocation.watchPosition(successCallback, errorCallback);
C. Geolocation.getCurrentPosition(successCallback, errorCallback);
D. Location.getPosition(successCallback, errorCallback);

Solution

  1. Step 1: Identify correct API usage

    The correct React Native API call for one-time location is Geolocation.getCurrentPosition with success and error callbacks.
  2. Step 2: Eliminate incorrect options

    watchPosition is for continuous tracking, navigator.location and Location.getPosition are not valid React Native APIs.
  3. Final Answer:

    Geolocation.getCurrentPosition(successCallback, errorCallback); -> Option C
  4. Quick Check:

    Correct method and parameters = Geolocation.getCurrentPosition(successCallback, errorCallback); [OK]
Hint: Use getCurrentPosition with success and error callbacks [OK]
Common Mistakes:
  • Using watchPosition for one-time location
  • Using browser navigator API in React Native
  • Incorrect method names or missing callbacks
3. What will be the output of the following code snippet in a React Native app if location permission is granted and location is successfully fetched?
Geolocation.getCurrentPosition(
  position => console.log(position.coords.latitude),
  error => console.log(error.message)
);
medium
A. Logs the user's latitude coordinate as a number
B. Logs the error message string
C. Throws a syntax error
D. Logs the entire position object

Solution

  1. Step 1: Analyze success callback

    The success callback logs position.coords.latitude, which is a number representing latitude.
  2. 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.
  3. Final Answer:

    Logs the user's latitude coordinate as a number -> Option A
  4. Quick Check:

    Success callback logs latitude number [OK]
Hint: Success callback logs latitude, error callback logs error [OK]
Common Mistakes:
  • Expecting entire position object logged
  • Confusing error callback with success callback
  • Assuming syntax error due to arrow functions
4. Identify the error in this React Native code snippet for tracking location changes:
const watchId = Geolocation.watchPosition(
  position => console.log(position.coords.longitude),
  error => console.log(error.message)
);
Geolocation.clearWatch(watchId);
medium
A. Error callback should be first argument
B. clearWatch is called immediately, stopping tracking instantly
C. watchPosition requires a third parameter for options
D. watchPosition does not return a watchId

Solution

  1. Step 1: Understand watchPosition behavior

    watchPosition starts tracking and returns a watchId to stop it later.
  2. Step 2: Analyze clearWatch usage

    Calling clearWatch(watchId) immediately after starting tracking stops it right away, so no updates will be received.
  3. Final Answer:

    clearWatch is called immediately, stopping tracking instantly -> Option B
  4. Quick Check:

    Immediate clearWatch stops tracking [OK]
Hint: Don't clearWatch immediately after watchPosition [OK]
Common Mistakes:
  • Calling clearWatch too soon
  • Mixing argument order in watchPosition
  • Assuming watchPosition returns nothing
5. You want to build a React Native app that tracks the user's location continuously but only updates the UI when the user moves more than 50 meters. Which approach is best to implement this efficiently?
hard
A. Use watchPosition with distanceFilter: 50 option to limit updates
B. Use getCurrentPosition repeatedly every second with a timer
C. Use watchPosition without options and filter distance manually in callback
D. Request location once and update UI only if user moves manually

Solution

  1. Step 1: Understand continuous tracking with filtering

    watchPosition supports options like distanceFilter to update only when user moves a set distance, saving resources.
  2. Step 2: Compare other options

    Using getCurrentPosition repeatedly wastes battery and CPU. Filtering manually after every update is less efficient. Requesting location once won't track movement.
  3. Final Answer:

    Use watchPosition with distanceFilter: 50 option to limit updates -> Option A
  4. Quick Check:

    distanceFilter option limits updates efficiently [OK]
Hint: Use distanceFilter option with watchPosition for efficient updates [OK]
Common Mistakes:
  • Polling location repeatedly with getCurrentPosition
  • Ignoring distanceFilter and filtering manually
  • Requesting location only once for continuous tracking
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard