4

如何避免“您在此页面上多次包含 Google Maps JavaScript API。这可能会导致意外错误。” 如果我使用 google-map-react 在另一个组件中显示地图和 react-places-autocomplete 以获取地址和坐标?

//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; 

地图为空白: 在此处输入图像描述 控制台中的错误:您已在此页面上多次包含 Google Maps JavaScript API。这可能会导致意外错误。

怎么解决?

我在项目中使用google-map-reactreact-places-autocomplete

4

2 回答 2

6

作为我在两个不同组件中使用谷歌地图 API 的特定用例的临时解决方案,我刚刚在 index.html 中添加了脚本:

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

根据react-places-autocomplete GitHub 页面上的文档,我这样做是为了避免该特定错误。

于 2018-07-17T08:44:48.577 回答
0

不幸的是,index.html 头部的链接导致了同样的错误。我找到了另一种解决方法。不是最好的解决方案,但现在有效:

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> }
            </>
    );
};

于 2021-09-01T07:59:57.877 回答