Search code examples
javascriptreactjsgoogle-mapsfrontendreact-google-maps

"Google Maps JavaScript API multiple times" error when using react-google-maps with react-places-autocomplete


I am using react-google-maps which requires a googleMapURL prop on it's component (which declares Google Maps JavaScript API) and react-places-autocomplete which requires a script with google maps js API too.

When I do both, I get the error "You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors".

I can't not declare the react prop or else the component doesn't work, and if I don't declare the script in index.html the react-places-autocomplete doesn't work.

How can I not get this error while using both these libraries?

I'm declaring this script at index.html inside public folder in a create-react-app project <script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&libraries=places"></script>

and the component which also declares the google maps api is the following

<WrappedMap
   googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${googleMapAPIKey}&v=3.exp&libraries=geometry,drawing,places`}
   loadingElement={<div className={styles.map} />}
   containerElement={<div className={styles.map} />}
   mapElement={<div className={styles.map} />}
/>

Solution

  • After asking in Leigh Halliday's youtube channel, I got the answer. You can use react-google-maps with a High Order Component called withGoogleMap that looks like it assumes you already have the google maps script installed on your site elsewhere. https://tomchentw.github.io/react-google-maps/#withgooglemap