0

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

2
  • The error is self-explanatory, you init map as null and then you are trying to modify it without null checking. Commented May 8, 2023 at 14:35
  • map is null when you call the .setCenter method. Make sure that is initialized before to use it. Commented May 8, 2023 at 15:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.