google api is already presented in react app

Viewed 3655

"google api is already presented"

Screen shoot error explanation

1.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=GOOGLE API KEY0&libraries=places"></script>
    <script>
        function init() {

            var options = {
              types: ['(cities)'],
              componentRestrictions: {country: "au"}
            };

            var input = document.getElementById('citySearch');
            var autocomplete = new google.maps.places.Autocomplete(input,options);
        }

        google.maps.event.addDomListener(window, 'load', init);
    </script>

2

  return (
    <div className="googleMapContainer">
      {console.log(window.google)}
      <LoadScript googleMapsApiKey={googleApiKey}>
        <div className="googleMap">
          <GoogleMap

how to handle this ? one api key is in index.html and other one is trying to use api key as props for component react-google-maps

4 Answers

Try <GoogleMap /> without <LoadScript /> in the code 2. Check more here

Alternatively you can move the LoadScript to a parent component that doesn't render much, preferably close to the root of your tree.

In case anyone else finds this google offers another API for loading the scripts rather than using <LoadScript>.

  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: 'YOUR API KEY HERE',
    libraries: ['geometry', 'drawing'],
  });

Then you can just use isLoaded later on:

{isLoaded && <GoogleMap
  onLoad={saveMap}
  mapContainerClassName={classes.mapContainer}
  mapContainerStyle={containerSize}
  center={DefaultCenterPoint}
  options={options}
>
  {mapItems}
</GoogleMap>}

This automatically handles if the maps API has already been loaded :)

You get an error message google API is already presented in react app when you try to load google maps API more than once. For your case, you loaded google API script <script ... /> from your first snippet. You also used <LoadScript .../> in your second snippet, which does the same.

So, to get rid of that error you have to load Google Maps API once.

you must use the first check if the script is laoded before loading it again here is the sample code on react.js {window.google === undefined ? <LoadScript><GoogleMap /></LoadScript> : <GoogleMap />}

Related