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.