Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Google Maps API (ReferenceError: google is not defined)

I'm using react-google-maps/api node module. I need to set the value of zoomControlOptions is TOP_LEFT but I ended up getting this error Uncaught ReferenceError: google is not defined. Here is the link to the repo.

I'm getting the error here

const options = {
  zoomControl: true,
  mapTypeControl: false,
  minZoom: 2,
  streetViewControl: false,
  zoomControlOptions: {
    position: google.maps.ControlPosition.TOP_LEFT, // google is undefined here
  },
};

Please help me :)

like image 866
Bablu Ahmed Avatar asked May 22 '26 23:05

Bablu Ahmed


2 Answers

This happens because you are rendering the Google Map before it's loaded.

Instead of using LoadScript, use useJsApiLoader.

import {
  GoogleMap,
  MarkerF,
  useJsApiLoader,
} from "@react-google-maps/api";


function RenderMap() {
  const { isLoaded } = useJsApiLoader({ googleMapsApiKey });
  if (!isLoaded) {
    return null;
  }
  // google is guaranteed to be defined now
  return <GoogleMap>...</GoogleMap>
}

useJsApiLoader has the following type signature:

declare function useJsApiLoader({ id, version, nonce, googleMapsApiKey, language, region, libraries, preventGoogleFontsLoading, mapIds, authReferrerPolicy, }: UseLoadScriptOptions): {
    isLoaded: boolean;
    loadError: Error | undefined;
};
like image 152
Hammad Ali Avatar answered May 24 '26 13:05

Hammad Ali


Try defining google variable explicitly like this:

const google = window.google;

Also, you may read out this answer as well

like image 38
AhmCho Avatar answered May 24 '26 13:05

AhmCho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!