Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To prevent this error message, you can use the Googlemaps react component in the following way:

  1. Define the Google Maps API key as a constant outside of the component. This ensures that the API key is only loaded once, instead of multiple times for each instance of the component.

  2. In the component's constructor, check if the Google Maps API script has already been loaded on the page. If it has not, load the script by adding it to the head of the document.

  3. During each map instance, instantiate it with the react-google-maps package and reference the Google Maps API key constant defined outside of the component.

This way, the script will only be loaded once and all map instances will share the same instance of the Google Maps JavaScript API, thereby preventing the error message.

Here's an example code snippet to illustrate the approach:

import React, { Component } from 'react';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';

const GOOGLE_MAPS_API_KEY = 'your_api_key_here';

class Map extends Component {
  constructor(props) {
    super(props);

    this.state = {
      scriptLoaded: false,
    };
  }

  componentDidMount() {
    if (window.google === undefined) {
      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}`;
      script.addEventListener('load', () => {
        this.setState({ scriptLoaded: true });
      });
      document.head.appendChild(script);
    } else {
      this.setState({ scriptLoaded: true });
    }
  }

  render() {
    const { scriptLoaded } = this.state;

    if (!scriptLoaded) {
      return <div>Loading...</div>;
    }

    const MyMap = withScriptjs(
      withGoogleMap(() => (
        <GoogleMap defaultCenter={{ lat: 37.7749, lng: -122.4194 }} defaultZoom={12}>
          <Marker position={{ lat: 37.7749, lng: -122.4194 }} />
        </GoogleMap>
      ))
    );

    return (
      <div style={{ height: '500px' }}>
        <MyMap
          googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}`}
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `100%` }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default Map;