ReactJs外部脚本-Google Maps

时间:2018-11-06 16:32:22

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

我试图将Google Maps添加到ReactJs Web应用程序,但没有成功。

我知道有一些反应组件可以包裹Google地图,但是它们不符合我的实际需求,因此我必须自己建造一个。我的问题是我不知道如何处理Google Maps正常工作所需的脚本标签:<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6maRCH9aI1K0sWA_FRdjIQv9AJgP7aQ0&callback=initMap" async defer></script>

我最初将其放在index.html中,但是在chrome devtools中启动我的应用程序时出现此错误:

Uncaught (in promise) 
Hc {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵    at new Hc (https://maps.googleapis.com/m…I1K0sWA_FRdjIQv9AJgP7aQ0&callback=initMap:124:108"}

我尝试使用fetch()来获取脚本,查看其实际含义,但是它要求使用CORS标头,并认为我不知道此请求所期望的确切参数,所以我认为这不是解决方案。

2 个答案:

答案 0 :(得分:1)

正如@Naismith所说,该错误是由于您的Google地图脚本include中的callback=initMap导致的。 因此,要使其正常工作,您必须像这样实现initMap函数:

<div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>

除了您要在组件中显示地图外,在这种情况下,您可以尝试这种方法,即为Google Maps API创建一个承诺,然后在Google Maps API的(全局)回调函数中解析该承诺。能跑。然后,在您的组件代码中,等待承诺得到解决,然后再继续。

class Map extends React.Component {
  getGoogleMaps() {
    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.366, lng: 131.044};
      const map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: laos
      });
      const marker = new google.maps.Marker({
        position: laos,
        map: map
      });
    });
  }

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

ReactDOM.render(
  <Map/>,
  document.getElementById('react')
);

答案 1 :(得分:0)

获取initMap的原因不是一个函数,这是因为在最后提供的脚本src的一部分是“ callback = initMap”。脚本加载完成后,这将运行一个名为initMap的函数。

如果您查看了Google网站上的文档,则它们具有示例功能,您必须将其放在Google地图的脚本标签上方。

https://developers.google.com/maps/documentation/javascript/tutorial