8

how can I avoid “You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.” if I am using google-map-react to display the map and react-places-autocomplete in another component to get the address and coordinates ?

//LocationMapPage  component that displays the map box and pass the props to it
class LocationMapPage extends Component {

  render() {
    let {latLng,name,address} = this.props.location;
    return (
        <MapBox lat={latLng.lat} lng={latLng.lng} name={name} address={address}/>
    )
  }

}

//MapBox component
import React from "react";
import GoogleMapReact from 'google-map-react';
import apiKey from "../../configureMap";


const Marker = () => <i className="fa fa-map-marker fa-2x text-danger" />

const MapBox = ({lat,lng, name, address}) => {
    const center = [lat,lng];
    const zoom = 14;
    return (  
        <div style={{ height: '300px', width: '100%' }}>
            <GoogleMapReact
            bootstrapURLKeys={{ key: apiKey }}
            defaultCenter={center}
            defaultZoom={zoom}
            >
            <Marker
                lat={lat}
                lng={lng}
                text={`${name}, ${address}`}
            />
            </GoogleMapReact>
      </div>
    );
}

export default MapBox; 

Map is blank: enter image description here The Error in the console:You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.

How to solve?

I am using google-map-react, react-places-autocomplete in the project.

Kamran
  • 819
  • 3
  • 14
  • 22

3 Answers3

7

AS temporary solution to my specific use case where I use the google map API's in two different components I have just added the script in the index.html:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> 

I did it in order to avoid that particular error as per of the documentation on the react-places-autocomplete GitHub page.

Kamran
  • 819
  • 3
  • 14
  • 22
  • This affects the initial time load of the page. But it works +1 – Herii Aug 01 '21 at 20:24
  • What is the permanent solution for this issue. There are so many questions related to this topic and all of them contain such temporary solutions but not permanent. – Shehzad Ahmed Aug 21 '23 at 09:50
2

You could set a global variable and load the Google JavaScript only if the global variable is not set:

<script type="text/javascript">
    if(document.isLoadingGoogleMapsApi===undefined) {
        document.isLoadingGoogleMapsApi=true;
        var script = document.createElement('script');
        script.src='https://maps.googleapis.com/maps/api/js?key=[your-key]&callback=[yourInitMethodName]&v=weekly';
        script.type='text/javascript';
        script.defer=true;
        document.getElementsByTagName('head')[0].appendChild(script);
    }else{
        [yourInitMethodName]();
    }
</script>

In my case there is an arbitrary number of maps in a web application (starting at 0) and the user can add additional maps at runtime. Most of the users do not use any map so loading it by default would cost unnecessarily loading time.

S. Doe
  • 685
  • 1
  • 6
  • 25
0

Unfortunately the link in the head of the index.html caused the same error. I found another workaround. Not the best solution, but works for now:

import React, { useEffect, useState } from 'react';
import GoogleMapReact from 'google-map-react';

export default () => {

    const [mapActive, setMapActive] = useState(false);

    useEffect(() => {
        const t = setTimeout(() => {
            setMapActive(true)
        }, 100);

        return () => {
            window.clearTimeout(t);
        };
    }, [])

    return (
            <>
                { mapActive && <GoogleMapReact
                    bootstrapURLKeys={ {
                        key: ...,
                        language: ...
                    } }
                    defaultCenter={ ... }
                    defaultZoom={ ... }
                >

                </GoogleMapReact> }
            </>
    );
};
Stewko
  • 1