javascript - 在 React 组件中使用谷歌地图

标签 javascript reactjs google-maps redux google-maps-markers

我正在尝试在 React Component 中使用 Google Map,但它似乎不起作用。 我目前指的是 https://developers.google.com/maps/documentation/javascript/adding-a-google-map

这是我的组件代码:

class ContactBody extends React.Component {
  componentWillMount() {
    const script = document.createElement("script");
    const API = 'AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw';
    script.src = `https://maps.googleapis.com/maps/api/js?key=${API}&callback=initMap`;
    script.async = true;

    document.body.appendChild(script);
  };

  initMap() {
    const uluru = {lat: -25.363, lng: 131.044};
    const map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: uluru
    });
    const marker = new google.maps.Marker({
      position: uluru,
      map: map
    });
  }

  render() {
    
    this.initMap();
    
    return (
      <div>
        <h1>Contact</h1>
        <div id="map" style={{width: 400, height: 300}}></div>
      </div>
    )
  }
}

ReactDOM.render(
  <ContactBody />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>

但是,当我运行它时,我收到“Uncaught ReferenceError: google is not defined”

有人能告诉我我的代码有什么问题吗?

谢谢。

最佳答案

您正在添加 <script>标记到您的文档以加载 Google Maps API,但您在运行 initMap 之前并没有等待它实际加载方法。由于尚未加载,google变量尚不存在。

您已将参数添加到脚本的 URL,callback , 值为 initMap . Google Maps API 将看到它并运行一个名为 initMap 的函数。一旦准备就绪。但是你的 initMap方法在全局范围内不可用,因此不会运行。

修复代码的一种方法是为 Google Maps API 做出 promise ,并在 Google Maps API 可以运行的(全局)回调函数中解决该 promise 。在您的组件代码中,您将等待 promise 在继续之前得到解决。

这可能看起来像这样:

class ContactBody extends React.Component {
  getGoogleMaps() {
    // If we haven't already defined the promise, define it
    if (!this.googleMapsPromise) {
      this.googleMapsPromise = new Promise((resolve) => {
        // Add a global handler for when the API finishes loading
        window.resolveGoogleMapsPromise = () => {
          // Resolve the promise
          resolve(google);

          // Tidy up
          delete window.resolveGoogleMapsPromise;
        };

        // Load the Google Maps API
        const script = document.createElement("script");
        const API = 'AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw';
        script.src = `https://maps.googleapis.com/maps/api/js?key=${API}&callback=resolveGoogleMapsPromise`;
        script.async = true;
        document.body.appendChild(script);
      });
    }

    // Return a promise for the Google Maps API
    return this.googleMapsPromise;
  }

  componentWillMount() {
    // Start Google Maps API loading since we know we'll soon need it
    this.getGoogleMaps();
  }

  componentDidMount() {
    // Once the Google Maps API has finished loading, initialize the map
    this.getGoogleMaps().then((google) => {
      const uluru = {lat: -25.363, lng: 131.044};
      const map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: uluru
      });
      const marker = new google.maps.Marker({
        position: uluru,
        map: map
      });
    });
  }

  render() {
    return (
      <div>
        <h1>Contact</h1>
        <div id="map" style={{width: 400, height: 300}}></div>
      </div>
    )
  }
}

ReactDOM.render(
  <ContactBody />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>

关于javascript - 在 React 组件中使用谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493960/

相关文章:

javascript - 如何将变量传递到 jquery.getScript 中?

javascript - 将名称之间带有点的数组映射到嵌套字段

reactjs - 类型 '{ src: String; }' 不可分配给类型 'SVGProps<SVGImageElement>

google-maps - 获取地址_组件

javascript - 在 vue.js 项目中风格化谷歌地图

Javascript - 使用文本输入框过滤数据

reactjs - 如何解决警告 "Warning: Can' t perform a React state update on an unmounted component."from setInterval function?

reactjs - 使用 ref react 打开选择文件对话框不起作用?

javascript - 如何检测长按谷歌地图标记?

javascript - 如果数组的任何元素等于 n 或数组的两个元素之和等于 n,则返回 true - 提高性能