I am using react-google-maps-api. Before that approach I tried to use a state to change center but google maps didn't see the initial state. Then I found this approach below on github.
const [map, setMap] = React.useState(null)
useEffect(() => {
country = hotels.find(h => h.country === choice);
map.setCenter(hotels.find(h => h.country === choice)?.center);
if (budgetValue == null) {
filteredFlights = country.hotels
} else {
filteredFlights = country?.hotels.filter(f => f.price * personCount < budgetValue);
}
setMarkers(filteredFlights);
}, [budgetValue]);
const onLoad = React.useCallback(function callback(map) {
setMap(map)
}, [])
const onUnmount = React.useCallback(function callback(map) {
setMap(null)
}, [])
return isLoaded ? (
<GoogleMap
mapContainerStyle={containerStyle}
center={tempCenter}
zoom={6}
onLoad={(map) => {
setMap(map);
}}
onUnmount={onUnmount}
>
{markers?.map((hotel, i) => {
return showMarker !== i ?
<Marker
onLoad={onLoad}
position={{ lat: hotel.lat, lng: hotel.lng }}
onMouseOver={() => setShowMarker(i)}
key={i}
/> :
<InfoWindowF
onLoad={onLoad}
position={{ lat: hotel.lat, lng: hotel.lng }}
key={i}
>
<a href={hotel.url} target="_blank">
<div onMouseOver={() => setShowMarker(i)} onMouseOut={() => setShowMarker(null)} style={divStyle}>
<h1>{hotel.name}</h1>
<img style={{ width: "200px", height: "100px" }} src={hotel.img} alt={hotel.name}></img>
<Typography>
Gecelik: {hotel.price}TL - {personCount} kişi: {hotel.price * personCount}TL
</Typography>
</div>
</a>
</InfoWindowF>
})}
<></>
</GoogleMap>
) : <></>
}
Trying to use map.setCenter() in useEffect but I get TypeError: Cannot read properties of null (reading 'setCenter'). Which I trying to achieve changing the center after useEffect runs. Thanks