0
0
React Nativemobile~20 mins

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

Choose your learning style9 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.