I have recently added a search bar to my React Google Maps application, but upon selecting a value from the search bar, the map is not re-rendering. I have attempted to set a key on the Google Map component, but it is not working. Below is the code for my application:
import React, { useState} from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';
import usePlacesAutocomplete, { getGeocode, getLatLng } from 'use-places-autocomplete';
const MapContainer = () => {
const [map, setMap] = useState(null);
const [selectedPlace, setSelectedPlace] = useState(null);
const [mapKey, setMapKey] = useState(new Date().getTime()); // Add mapKey state
const containerStyle = {
width: '100%',
height: '400px',
};
const center = {
lat: 37.7749,
lng: -122.4194,
};
const onLoad = (map) => {
setMap(map);
};
const handleSelect = async (address) => {
try {
const results = await getGeocode({ address });
const { lat, lng } = await getLatLng(results[0]);
setSelectedPlace({ address, lat, lng });
setMapKey(new Date().getTime()); // Update mapKey state
} catch (error) {
console.error('Error:', error);
}
};
const handleLoadScriptError = (error) => {
console.error('Load Error:', error);
};
return (
<LoadScript googleMapsApiKey="YOUR_API_KEY" libraries={['places']} onError={handleLoadScriptError}>
<div style={containerStyle}>
<GoogleMap key={mapKey} mapContainerStyle={containerStyle} center={center} zoom={10} onLoad={onLoad}>
{selectedPlace && <Marker position={{ lat: selectedPlace.lat, lng: selectedPlace.lng }} />}
</GoogleMap>
<PlacesSearchBox onSelect={handleSelect} />
</div>
</LoadScript>
);
};
const PlacesSearchBox = ({ onSelect }) => {
const { ready, value, suggestions: { status, data }, setValue, clearSuggestions } = usePlacesAutocomplete();
const handleInputChange = (e) => {
setValue(e.target.value);
};
const handleSelect = (address) => {
setValue(address, false);
clearSuggestions();
onSelect(address);
};
return (
<div>
<input type="text" value={value} onChange={handleInputChange} placeholder="Search..." />
{status === 'OK' && (
<ul>
{data.map((suggestion, index) => (
<li key={index} onClick={() => handleSelect(suggestion.description)}>
{suggestion.description}
</li>
))}
</ul>
)}
</div>
);
};
export default MapContainer;
I was not updating center position. After setting the selected values of lat/lng, its started to work.
const center = {
lat: 37.7749,
lng: -122.4194,
};