Rendering a Google Map without react-google-map

前端 未结 4 816
忘了有多久
忘了有多久 2021-01-11 21:47

Has anyone been able to render a google map using React and not using the react-google-map plugin? I\'m trying something like this:

var MapTab = React.creat         


        
4条回答
  •  半阙折子戏
    2021-01-11 22:05

    With componentDidMount you know you map container div has loaded, but you are not guaranteed that the external maps api has loaded yet. Google provides you the option to give a callback function (initMap() in their examples).

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

    Now you can proceed as follows, After your map component did mount you can:

    1. window.initMap = this.initMap to make initMap from react available for Google maps to callback to.
    2. load the google maps JS with initMap parameter.
    3. In this.initMap in your component you can do your map stuff, because now you know your container ánd Google API have loaded.

      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=&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 (
      ) } } module.exports = Radium(Map)

提交回复
热议问题