How to load the google maps api [removed] in my react app only when it is required?

前端 未结 3 465
渐次进展
渐次进展 2021-01-04 13:04

I want to try and use the google maps API to show a map but I\'m wondering if there\'s a better way to load the

3条回答
  •  误落风尘
    2021-01-04 13:31

    Updates Oct 6, 2019: The example code is still working well, I have just updated them to use non-decorator syntax.


    This is what I make it worked in my recent project. I used react-async-script-loader component.

    import React from 'react';
    import scriptLoader from 'react-async-script-loader';
    
    class Maps extends React.Component {
      constructor(props) {
        super(props);
        this.map = null;
      }
    
      componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
        if (isScriptLoaded && !this.props.isScriptLoaded) {
          // load finished
          if (isScriptLoadSucceed) {
            this.map = new google.maps.Map(this.refs.map, {
              center: { lat: 10.794234, lng: 106.706541 },
              zoom: 20
            });
    
            if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(
                position => {
                  const pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                  };
    
                  this.map.setCenter(pos);
    
                  const marker = new google.maps.Marker({
                    position: pos,
                    map: this.map,
                    title: 'Hello World!'
                  });
                },
                () => {
                  console.log('navigator disabled');
                }
              );
            } else {
              // Browser doesn't support Geolocation
              console.log('navigator disabled');
            }
          } else this.props.onError();
        }
      }
    
      render() {
        return (
          
    {!this.map &&
    Loading...
    }
    ); } } export default scriptLoader(['https://maps.googleapis.com/maps/api/js?key=API_KEY'])(Maps);

提交回复
热议问题