To retrieve the current mobile map position in a React Native application, you can use the react-native-maps
library along with the device’s geolocation API. Make sure to install the necessary dependencies before running the code:
bash
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import MapView, { Marker } from 'react-native-maps';
import Geolocation from 'react-native-geolocation-service';
const MapScreen = () => {
const [region, setRegion] = useState({
latitude: 0,
longitude: 0,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
});
useEffect(() => {
// Get current location when the component mounts
getCurrentLocation();
}, []);
const getCurrentLocation = () => {
Geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords;
setRegion({
latitude,
longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
});
},
error => console.error('Error getting current location:', error),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
};
return (
<View style={{ flex: 1 }}>
<MapView style={{ flex: 1 }} region={region}>
<Marker coordinate={{ latitude: region.latitude, longitude: region.longitude }} />
</MapView>
<View style={{ position: 'absolute', top: 20, left: 10 }}>
<Text style={{ color: 'white', fontSize: 16 }}>
Current Location: {region.latitude.toFixed(4)}, {region.longitude.toFixed(4)}
</Text>
</View>
</View>
);
};
export default MapScreen;