Javascript 在React组件中使用googlemap

Javascript 在React组件中使用googlemap,javascript,reactjs,google-maps,redux,google-maps-markers,Javascript,Reactjs,Google Maps,Redux,Google Maps Markers,我试图在React组件中使用GoogleMap,但它似乎不起作用。 我现在指的是 以下是我的组件的代码: 类ContactBody扩展了React.Component{ 组件willmount(){ 常量脚本=document.createElement(“脚本”); 常量API='AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw'; script.src=`https://maps.googleapis.com/maps/api/js?key=${API}&ca

我试图在React组件中使用GoogleMap,但它似乎不起作用。 我现在指的是

以下是我的组件的代码:

类ContactBody扩展了React.Component{
组件willmount(){
常量脚本=document.createElement(“脚本”);
常量API='AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw';
script.src=`https://maps.googleapis.com/maps/api/js?key=${API}&callback=initMap`;
script.async=true;
document.body.appendChild(脚本);
};
initMap(){
constuluru={lat:-25.363,lng:131.044};
const map=new google.maps.map(document.getElementById('map'){
缩放:4,
中心:乌卢鲁
});
const marker=new google.maps.marker({
职位:乌卢鲁,
地图:地图
});
}
render(){
this.initMap();
返回(
接触
)
}
}
ReactDOM.render(
,
document.getElementById('react')
);

您正在向文档中添加一个
标记以加载Google Maps API,但在运行
initMap
方法之前,您不会等待它实际加载。由于尚未加载,
google
变量尚不存在

您已经向脚本的URL添加了一个参数,
callback
,其值为
initMap
。GoogleMapsAPI将看到这一点,并在准备好后运行名为
initMap
的函数。但是您的
initMap
方法在全局范围内不可用,因此将不会运行

修复代码的一种方法是为GoogleMapsAPI做出承诺,并在GoogleMapsAPI可以运行的(全局)回调函数中解析该承诺。在组件代码中,您需要等待承诺得到解决,然后才能继续

可能看起来像这样:

类ContactBody扩展了React.Component{
getGoogleMaps(){
//如果我们还没有定义承诺,请定义它
如果(!this.googleMapsPromise){
this.googleMapsPromise=新承诺((解决)=>{
//为API完成加载时添加全局处理程序
window.resolveGoogleMapsPromise=()=>{
//兑现诺言
解决(谷歌);
//收拾
删除window.resolveGoogleMapsPromise;
};
//加载谷歌地图API
常量脚本=document.createElement(“脚本”);
常量API='AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw';
script.src=`https://maps.googleapis.com/maps/api/js?key=${API}&callback=resolveGoogleMapsPromise`;
script.async=true;
document.body.appendChild(脚本);
});
}
//返回谷歌地图API的承诺
返回此文件。谷歌地图预览;
}
组件willmount(){
//启动谷歌地图API加载,因为我们知道我们很快就会需要它
这个.getGoogleMaps();
}
componentDidMount(){
//一旦谷歌地图API完成加载,初始化地图
这个.getGoogleMaps().then((google)=>{
constuluru={lat:-25.363,lng:131.044};
const map=new google.maps.map(document.getElementById('map'){
缩放:4,
中心:乌卢鲁
});
const marker=new google.maps.marker({
职位:乌卢鲁,
地图:地图
});
});
}
render(){
返回(
接触
)
}
}
ReactDOM.render(
,
document.getElementById('react')
);

我就是这样做的:

import React from 'react';

export default class GoogleMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mapIsReady: false,
    };
  }

  componentDidMount() {
    const ApiKey = 'XXXXXXXXXXXXXXXXXXXX';
    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=${ApiKey}`;
    script.async = true;
    script.defer = true;
    script.addEventListener('load', () => {
      this.setState({ mapIsReady: true });
    });

    document.body.appendChild(script);
  }

  componentDidUpdate() {
    if (this.state.mapIsReady) {
      // Display the map
      this.map = new window.google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 12,
        mapTypeId: 'roadmap',
      });
      // You also can add markers on the map below
    }
  }

  render() {
    return (
      <div id="map" />
    );
  }
}
从“React”导入React;
导出默认类GoogleMap扩展React.Component{
建造师(道具){
超级(道具);
此.state={
地图编辑:错,
};
}
componentDidMount(){
常量ApiKey='xxxxxxxxxxxxxxxxxxxxx';
const script=document.createElement('script');
script.src=`https://maps.googleapis.com/maps/api/js?key=${ApiKey}`;
script.async=true;
script.defer=true;
script.addEventListener('load',()=>{
this.setState({mapIsReady:true});
});
document.body.appendChild(脚本);
}
componentDidUpdate(){
if(this.state.mapIsReady){
//显示地图
this.map=newwindow.google.maps.map(document.getElementById('map'){
中心:{纬度:-34.397,液化天然气:150.644},
缩放:12,
mapTypeId:“路线图”,
});
//您还可以在下面的地图上添加标记
}
}
render(){
返回(
);
}
}

对于那些遇到错误的人来说,google并没有定义在eslint提到的错误之上,请继续定义

const google = window.google;

尝试在页面顶部键入此内容(对我有用)-/*全局google*/

如果您在index.html中包含google API脚本,则无需在componentDidMount()中创建元素。 你可以这样做-

import React from 'react';
export default class GoogleMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mapIsReady: false,
    };
  }

  componentDidMount() {
    //Load Map after DOM is loaded
    window.onload = this.setState({mapIsReady : true});
  }

  componentDidUpdate() {
    if (this.state.mapIsReady) {
      // Display the map
      this.map = new window.google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 12,
        mapTypeId: 'roadmap',
      });
      // You also can add markers on the map below
    }
  }

  render() {
    return (
      <div id="map"></div>
    );
  }
}
从“React”导入React;
导出默认类GoogleMap扩展React.Component{
建造师(道具){
超级(道具);
此.state={
地图编辑:错,
};
}
componentDidMount(){
//加载DOM后加载映射
window.onload=this.setState({mapIsReady:true});
}
componentDidUpdate(){
if(this.state.mapIsReady){
//显示地图
this.map=newwindow.google.maps.map(document.getElementById('map'){
中心:{纬度:-34.397,液化天然气:150.644},
缩放:12,
mapTypeId:“路线图”,
});
//您还可以在下面的地图上添加标记
}
}
render(){
返回(
);
}
}
将脚本添加到head标记(我的建议是)然后将window.initMap等同于初始化map函数,因为在脚本src中定义(
callback=initMap“
)一个名为“initMap”的全局函数

import React,{useffect}来自“React”;
从“react Helmet”导入{Helmet};
常量映射=()=>{
useffect(()=>{
window.initMap=()=>{
新的google.maps.Map(document.getElementById('Map'),
... lang-js
if (process.browser) { // check browser environment
  window.initMap = (): void => {
    new google.maps.Map(document.getElementById('map'), {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8,
    });
  };
}
...
                 import React, { useState, useEffect } from 'react';

                  function App() {

                       useEffect(() => {


                            const googleMapScript = document.createElement('script');
                            googleMapScript.src=`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLEMAPS_API_KEY}&libraries=places&callback=initMap`;
                            googleMapScript.async = true;
                            window.document.body.appendChild(googleMapScript);

                      }); 

    return (
              process.env.REACT_APP_GOOGLEMAPS_API_KEY
              REACT_APP_GOOGLEMAPS_API_KEY=AIzajfU2J8m4vE