【问题标题】:Rendering a Google Map without react-google-map在没有 react-google-map 的情况下渲染谷歌地图
【发布时间】:2016-04-19 04:23:22
【问题描述】:

有没有人能够使用 React 而不是使用 react-google-map 插件来渲染谷歌地图?我正在尝试这样的事情:

var MapTab = React.createClass({

render: function() {

    return  <div className="map-container">
       <div id='map' ></div>
     </div>

},

componentDidMount: function(){

        console.log("Hello")



window.onload = function(){
    (function initMap() {
        var markers = [];
        var geocoder = new google.maps.Geocoder();

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: {lat: 37.7749300, lng: -122.4194200}
        });
    })(); 
}


}// end of cdm;
}); 
module.exports = MapTab;

我尝试过的任何方法都没有奏效。我也尝试过使用 refs 捕获地图,但这也没有渲染地图。我也将谷歌地图脚本放在标题中(带有密钥),并验证密钥在 vanilla js 项目中有效。

【问题讨论】:

  • 这个有更新吗?
  • 我很好奇这种方法的局限性/优势是什么?我发现 react-google-map 文档很难遵循。

标签: google-maps-api-3 reactjs


【解决方案1】:

您可以使用 React Refs 轻松渲染谷歌地图,这是与第三方库集成时的理想解决方案。像这样:

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      // no state for now..
    }

    // Use createRef() to create a reference to the DOM node we want
    this.myMapContainer = React.createRef()
  }

  componentDidMount() {
    // Instead of using: document.getElementById, use the ref we created earlier to access the element
    let map = new google.maps.Map(this.myMapContainer.current, {
      center: { lat: -34.9973268, lng: -58.582614 },
      scrollwheel: false,
      zoom: 4
    })
  }

  render() {
    return (
      <div className="container">
        <div ref={this.myMapContainer} id="map"></div>
        <div id="text"><p>Google Maps now requires the use of a valid API Key.
          That's why you see the popup window "This page can't load Google Maps correctly."</p>
          <a href="https://developers.google.com/maps/documentation/javascript/get-api-key">Go get one!</a>
        </div>
      </div>
    )
  }
}

Working Example here

注意:不要忘记放置调用 Google Maps API 的 &lt;script&gt;。如果您使用create-react-app 创建项目,则可以将脚本放在public/index.html

【讨论】:

    【解决方案2】:

    使用 componentDidMount,您知道您的地图容器 div 已加载,但您不能保证外部地图 api 已加载。 Google 为您提供了提供回调函数的选项(在他们的示例中为 initMap())。

    https://maps.googleapis.com/maps/api/js?key=&callback=initMap

    现在您可以进行如下操作,在您的地图组件挂载后,您可以:

    1. window.initMap = this.initMap 使 initMap 从 react 可用于 Google 地图回调。
    2. 使用 initMap 参数加载谷歌地图 JS。
    3. 在组件的 this.initMap 中,您可以执行地图操作,因为现在您知道您的容器和 Google API 已加载。

      const React = require('react')
      const PropTypes = require('prop-types')
      import Reflux from 'reflux'
      const Radium = require('radium')
      
      class Map extends Reflux.Component {
      
          constructor(props) {
              super(props)
              this.loadJS = this.loadJS.bind(this)
              this.initMap = this.initMap.bind(this)
          }
      
          componentDidMount() {
              window.initMap = this.initMap;
              if (typeof google === 'object' && typeof google.maps === 'object') {
                  this.initMap()
              } else {
                  this.loadJS('https://maps.googleapis.com/maps/api/js?key=<API_KEY>&callback=initMap')   
              }
          }
      
          // https://github.com/filamentgroup/loadJS/blob/master/loadJS.js
          loadJS(src) {
              var ref = window.document.getElementsByTagName("script")[0];
              var script = window.document.createElement("script");
              script.src = src;
              script.async = true;
              ref.parentNode.insertBefore(script, ref);
          }
      
          initMap() {
              var map = new google.maps.Map(this.refs.map, {
                center: {lat: -34.397, lng: 150.644},
                zoom: 8
              })
          }
      
          render() {
              return (<div ref='map'></div>)
          }
      
      }
      module.exports = Radium(Map)
      

    【讨论】:

      【解决方案3】:

      看来你对 React 组件生命周期还不熟悉。

      https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle

      或者这个:http://busypeoples.github.io/post/react-component-lifecycle/(这里有 react 方法执行的顺序表)

      其实在componentDidMount()中(“DID-mount”表示该元素已经在页面上,所以可以开始绑定事件)

      React Component 的想法很有趣,所以我们不需要使用 javascript 的 "window.onload()" 或 jQuery 的 "$(document).ready() "

      因此,您的代码可以修改如下:

      render: function() {
          return  <div className="map-container">
             <div id='map' ></div>
           </div>
      },
      
      componentDidMount: function(){
      
          console.log("Hello")
      
          var markers = [];
          var geocoder = new google.maps.Geocoder();
      
          var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 12,
              center: {lat: 37.7749300, lng: -122.4194200}
          });
      
      }// end of cdm;
      

      PS:此外,为了使地图出现,您需要正确设置地图容器和地图的样式(这需要像素高度,在您的“0 px 宽度的情况,也许您也需要设置宽度 - 以 px 或 100% 为单位)尽管可以随意设置它们的样式!

      【讨论】:

        【解决方案4】:

        摆脱window.onload。在调用componentDidMount 方法时,窗口已经加载,所以你的initMap() 函数永远不会触发。

        【讨论】:

        • 这并不能解决问题,但我确实摆脱了 window.onload。我发现地图的渲染宽度为 0px,所以我修复了现在我看到的只是地图应该在的灰色框——没有错误或任何东西。
        猜你喜欢
        • 1970-01-01
        • 2019-08-06
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 2023-02-22
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多