React Google 地图和 React Places 自动完成:您已在此页面上多次包含 [=11th=] 地图 JavaScript API

React Google Map and React Places Auto Complete: You have included the Google Maps JavaScript API multiple times on this page

我需要为我的 2 个组件包含两次 google 映射 API。因此,出现此错误您在此页面上多次包含 Google 地图 JavaScript API。我无法删除 index.html 中的第一个 google 映射 API link,因为我需要它来自动完成。我现在的问题是如何在 googleMapURL 中包含另一个 google 映射 API link 而不会导致此错误?

Google 地图组件

const MapWrapped = withScriptjs(withGoogleMap(Map));
<MapWrapped
        googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAP_API_KEY}&v=3.exp&libraries=geometry,drawing,places`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />

为了使 Google 地图 API 正常工作,您的代码中应该只有一个 Google 地图脚本标记。由于您同时使用了 react-google-maps 和 place autocomplete,我建议您将 Google 地图组件和 MapWrapped 放在 index.js 中,并从 [=] 中删除脚本标签20=]。这样你就只能使用一个脚本标签。我不确定您是如何在代码中使用地点自动完成功能的,但是如果您使用的是 react-places-autocomplete 库,则可以像 sample code 和下面的代码片段中的那样进行操作:

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import { withScriptjs } from 'react-google-maps';
import Map from './Map';

const App = () => {
  const MapLoader = withScriptjs(Map);

  return (
    <MapLoader
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
      loadingElement={<div style={{ height: `100%` }} />}
    />
  );
};

render(<App />, document.getElementById('root'));

Map.js

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

import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng
} from 'react-places-autocomplete';

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

    this.state = {
      isOpen: false,
      coords: { lat: 40.756795, lng: -73.954298 },
      address: ''
    };
  }
  handleChange = address => {
    this.setState({ address });
  };

  handleSelect = address => {
    geocodeByAddress(address)
      .then(results => getLatLng(results[0]))
      .then(latLng =>
        this.setState({
          coords: latLng
        })
      )
      .catch(error => console.error('Error', error));
  };

  handleToggleOpen = () => {
    this.setState({
      isOpen: true
    });
  };

  handleToggleClose = () => {
    this.setState({
      isOpen: false
    });
  };

  render() {
    const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap defaultCenter={this.state.coords} defaultZoom={13}>
        <Marker
          key={this.props.index}
          position={this.state.coords}
          onClick={() => this.handleToggleOpen()}
        >
          {this.state.isOpen && (
            <InfoWindow
              onCloseClick={this.props.handleCloseCall}
              options={{ maxWidth: 100 }}
            >
              <span>This is InfoWindow message!</span>
            </InfoWindow>
          )}
        </Marker>
      </GoogleMap>
    ));

    return (
      <div>
        <PlacesAutocomplete
          value={this.state.address}
          onChange={this.handleChange}
          onSelect={this.handleSelect}
        >
          {({
            getInputProps,
            suggestions,
            getSuggestionItemProps,
            loading
          }) => (
            <div>
              <input
                {...getInputProps({
                  placeholder: 'Search Places ...',
                  className: 'location-search-input'
                })}
              />
              <div className="autocomplete-dropdown-container">
                {loading && <div>Loading...</div>}
                {suggestions.map(suggestion => {
                  const className = suggestion.active
                    ? 'suggestion-item--active'
                    : 'suggestion-item';
                  // inline style for demonstration purpose
                  const style = suggestion.active
                    ? { backgroundColor: '#fafafa', cursor: 'pointer' }
                    : { backgroundColor: '#ffffff', cursor: 'pointer' };
                  return (
                    <div
                      {...getSuggestionItemProps(suggestion, {
                        className,
                        style
                      })}
                      key={suggestion.placeId}
                    >
                      <span>{suggestion.description}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </PlacesAutocomplete>
        <GoogleMapExample
          containerElement={<div style={{ height: `500px`, width: '500px' }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default Map;