如何在反应组件中嵌入谷歌地图

时间:2017-09-04 13:39:56

标签: javascript reactjs google-maps google-maps-api-3

我一直试图在反应组件中嵌入谷歌地图但没有成功。我不确定为什么和在线教程似乎已经过时版本的反应和谷歌地图。

我的组件如下。 HTML文档取自google maps documentation

import React from 'react'
import scriptLoader from 'react-async-script-loader'

class Gmaps extends React.Component {
  constructor(props) {
    super(props)
  }

  componentDidMount() {
    var uluru = {lat: -25.363, lng: 131.044};
    this.map = new google.maps.Map(this.refs.map, {
      zoom: 4, 
      center: uluru
    })
  }

  render() {
    return (
      <div>   
        <h3>My Google Maps Demo</h3>
        <div id="map" ref="map"></div>
        <script>
          {function initMap() {
            var uluru = {lat: -25.363, lng: 131.044};
            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 4,
              center: uluru
            });
            var marker = new google.maps.Marker({
              position: uluru,
              map: map
            });
          }}
        </script>
      </div>
      )
    }
  }

export default scriptLoader(
['https://maps.googleapis.com/maps/api/js?key=APIKEY']
) (Gmaps)

显然我需要使用react ref加载地图,但不太确定如何。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

来自here

的来源
class Gmaps extends React.Component {

    ...

    componentDidMount() {
        // Connect the initMap() function within this class to the global window context,
        // so Google Maps can invoke it
        window.initMap = this.initMap;
        // Asynchronously load the Google Maps script, passing in the callback reference
        loadJS('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap')
    }

    initMap() {
        map = new google.maps.Map(this.refs.map.getDOMNode(), { ... });
    }

    render() {
            return (
                <div>
                    ...
                    <div ref="map" style="height: '500px', width: '500px'"><⁄div>
                <⁄div>
            );
    }
})

function 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);
}