I am using react-native-maps
to let users select a location from the map. However, I have to click multiple times before the location gets selected, and the marker updates its position. Is this a performance issue, or is there a problem with my code?
Expected Behavior:
When a user clicks on a location on the map, the marker should immediately move to the new location, and the location name should be insertedd to the selectedLocation
state.
Here’s my component:
const LocationScreen = () => {
const [selectedLocation, setSelectedLocation] = useState('');
const [markerCoordinates, setMarkerCoordinates] = useState({ latitude: 24.4539, longitude: 54.3773 });
const API_KEY = '893*********************';
const handleMapPress = async (event) => {
const { latitude, longitude } = event.nativeEvent.coordinate;
try {
const response = await axios.get(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=${API_KEY}`);
const components = response.data.results[0].components;
const location =
components.town ||
components.city ||
components.village ||
components.hamlet ||
components.locality ||
components.country;
if (location) {
setSelectedLocation(location);
setMarkerCoordinates({ latitude, longitude });
} else {
setSelectedLocation('Unknown location');
}
} catch (error) {
console.error("Error fetching location data: ", error);
}
};
return (
<View style={styles.container}>
<StatusBar
backgroundColor="transparent"
barStyle="dark-content"
translucent={true}
/>
<SafeAreaView style={styles.form}>
<View style={styles.head}>
<BackArrow /> {/* Assuming BackArrow is a valid component */}
<Text style={styles.title}>Location</Text>
</View>
<MapView
style={{ width: '100%', height: "100%" }}
initialRegion={{
latitude: 24.4539,
longitude: 54.3773,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
onPress={handleMapPress}
>
{markerCoordinates && (
<Marker
coordinate={markerCoordinates}
title={selectedLocation}
/>
)}
</MapView>
{selectedLocation && (
<View style={styles.selectedLocationContainer}>
<Text style={styles.selectedLocationText}>Selected Location: {selectedLocation}</Text>
</View>
)}
</SafeAreaView>
</View>
);
};
export default LocationScreen;
medHedi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.