Search code examples
javascriptreactjsgoogle-maps-api-3

Cannot read properties of undefined (reading 'maps') using React and @google-maps-api


Currently I'm trying to find a way to make markers and infoboxes for an array of points with longitude and latitude. The code runs fine for the first time but if I were to reload the page, the error 'Cannot read properties of undefined (reading 'maps')' comes up. Not sure what's causing this problem.

Any tips or advice on this will be great

function Map() {
  const markers = [
    {
      id: 1,
      name: "Chicago, Illinois",
      position: { lat: 41.881832, lng: -87.623177 }
    },
    {
      id: 2,
      name: "Denver, Colorado",
      position: { lat: 39.739235, lng: -104.99025 }
    },
    {
      id: 3,
      name: "Los Angeles, California",
      position: { lat: 34.052235, lng: -118.243683 }
    },
    {
      id: 4,
      name: "New York, New York",
      position: { lat: 40.712776, lng: -74.005974 }
    }
  ];

  const [activeMarker, setActiveMarker] = useState(null);

  const handleActiveMarker = (marker) => {
    if (marker === activeMarker) {
      return;
    }
    setActiveMarker(marker);
  };

  const handleOnLoad = (map) => {
    const bounds = new google.maps.LatLngBounds();
    markers.forEach(({ position }) => bounds.extend(position));
    map.fitBounds(bounds);
  };

  return (
    <div>
        <GoogleMap onLoad={handleOnLoad} onClick={() => setActiveMarker(null)} mapContainerClassName="map-container">
          {markers.map(({id, name, position}) => (
            <MarkerF
            key={id} 
            position={position} 
            icon={"http://maps.google.com/mapfiles/ms/icons/blue-dot.png"} 
            onClick={() => handleActiveMarker(id)}
            >
              {activeMarker === id ? (
                <InfoWindowF onCloseClick={() => setActiveMarker(null)}>
                  <div>{name}</div>
                </InfoWindowF>
              ) : null}
            </MarkerF>
          ))}
        </GoogleMap>

    </div>

  );
}

I tried using {markers && markers.map(...)} but it still says that error

I'm expecting it to place markers with infoboxes following the data from markers


Solution

  • As for the solution to this problem. It was a problem with asynchronous situations. The idea was that React wasn't storing the data that was being called from a Flask API fast enough which caused it not to have any data in "maps" at all, therefore resulting in that error. A solution is to instead call the API using "useReducer" rather than "useState"