I am working on a React Native project where I have integrated a Google Map with a cursor, and everything works fine. I added a GooglePlacesAutocomplete component to provide a search bar for the user to search for locations. However, the search bar does not work. When I type something into it, nothing appears.
Additionally, I created a function handleLocationSelect
to link the GooglePlacesAutocomplete with the map cursor so that when the user searches for something, the cursor automatically moves to the location’s latitude and longitude. I would like to know if this function is implemented correctly.
const Location= () => {
const [selectedLocation, setSelectedLocation] = useState('');
const [markerCoordinates, setMarkerCoordinates] = useState({ latitude: 24.4539, longitude: 54.3773 });
const API_KEY = '893d1465300549d88490773eddb7f9f2';
const GOOGLE_PLACES_API_KEY = 'AIzaSyAnmKvj5E4qVZJTGtVJtMU4B2P3op8Ce0o';
const handleMapPress = async (event) => {
const { latitude, longitude } = event.nativeEvent.coordinate;
setMarkerCoordinates({ latitude, longitude });
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);
} else {
setSelectedLocation('Unknown location');
}
} catch (error) {
console.error('Error fetching location data: ', error);
}
};
const handleLocationSelect = (data, details = null) => {
const { lat, lng } = details.geometry.location;
setMarkerCoordinates({ latitude: lat, longitude: lng });
setSelectedLocation(details.name);
};
return (
<View style={styles.container}>
<StatusBar
backgroundColor="transparent"
barStyle="dark-content"
translucent={true}
/>
<SafeAreaView style={styles.form}>
<View style={styles.head}>
<BackArrow />
<Text style={styles.title}>Location</Text>
</View>
<View style={{ width: '90%' }}>
<GooglePlacesAutocomplete
placeholder='Search'
fetchDetails={true}
onPress={handleLocationSelect}
query={{
key: GOOGLE_PLACES_API_KEY,
language: 'en',
}}
styles={{
container: { width: '100%', zIndex: 1 },
textInput: {
height: 51,
borderRadius: 15,
color: Colors.SmokeBlue,
fontSize: 13,
fontFamily: FONTS.PoppinsRegular,
marginTop: '10%',
paddingHorizontal: 15,
},
}}
/>
</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 Location;