繁体   English   中英

由于谷歌地图<script> tag does not read create-react-app's public/index.html file, what library could I use?

[英]Since Google map's <script> tag does not read create-react-app's public/index.html file, what library could I use?

我一直在使用 Webpack 和 Googlemaps 在线学习一门课程,我需要将它带到我的 Create-React-App 应用程序中,但我知道 create-react-app 不会读取带有 public/index 中的 api 键的脚本标签.html 文件。 是否有解决方法而不是使用谷歌地图 npm 包? 我真的很感激任何正确方向的提示。

这是我的带有 API_KEY 的脚本标签:

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key='API_KEY'">
</script>

这是我的 componentDidMount() 中的 google maps 对象:

componentDidMount(){

  const {properties, activeProperty} = this.props;

  const {latitude, longitude} = activeProperty;

  this.map = new google.maps.Map(this.refs.map, {
      center: {lat: latitude, lng: longitude},
      mapTypeControl: false,
      zoom: 14
  });

  this.createMarkers(properties);

}

要管理 Google 地图库参数,您可以考虑像一些流行的图书馆那样按需加载脚本资源,而不是通过index.html引用 Google 地图库。

例如,使用ReactDependentScript组件Google Maps API 可以像这样加载:

class App extends Component {
  render() {

    const MAP_KEY = "--YOUR-KEY-GOES-HERE--";

    return (
      <div>
        <ReactDependentScript scripts={[`https://maps.googleapis.com/maps/api/js?key=${MAP_KEY}`]}>
          <Map center={{ lat: -34.397, lng: 150.644 }} zoom={3} />
        </ReactDependentScript>
      </div>
    );
  }
}

这是一个演示供您参考

你能写你的整个组件/类吗? 你在哪里注入你的脚本? 如果你在静态 html 中做了,你将需要 window.google。

我为你写了一个例子,记得在 public/index.html 中用 API 密钥注入你的脚本

class App extends React.Component {
  componentDidMount() {
    this.map = new window.google.maps.Map(this.map, {
      center: { lat: 41.3851, lng: 2.1734 },
      mapTypeControl: false,
      zoom: 14
    });
  }

  render() {
    return (
      <div>
        <div
          style={{ width: "600px", height: "600px" }}
          ref={e => (this.map = e)}
        />
      </div>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM