简体   繁体   中英

How to import google map in react project

I a using webpack and reactjs in my project and now I want to integrate google map api. First I added "react-google-maps": "^4.9.1" on my package.json file. Below is my component class.

import React, {PropTypes, Component} from 'react';

import { GoogleMap, Marker, SearchBox } from "react-google-maps";
import shouldPureComponentUpdate from 'react-pure-render/function';

const greatPlaceStyle = {
  // initially any map object has left top corner at lat lng coordinates
  // it's on you to set object origin to 0,0 coordinates
  position: 'absolute',
  width: 512,
  height: 512,
  left: 512 / 2,
  top: 512 / 2,

  border: '5px solid #f44336',
  borderRadius: 512,
  backgroundColor: 'white',
  textAlign: 'center',
  color: '#3f51b5',
  fontSize: 16,
  fontWeight: 'bold',
  padding: 4
};

export default class SimpleMapPage extends Component {
  static defaultProps = {
    center: {lat: 59.938043, lng: 30.337157},
    zoom: 1,
    greatPlaceCoords: {lat: 59.724465, lng: 30.080121}
  };

  shouldComponentUpdate = shouldPureComponentUpdate;

  constructor(props) {
    super(props);
  }

  render() {
    return (
       <GoogleMap>

        defaultCenter={this.props.center}
        defaultZoom={this.props.zoom}>

        <MyGreatPlace lat={59.955413} lng={30.337844} text={'A'} />
        <MyGreatPlace {...this.props.greatPlaceCoords} text={'B'} />

      </GoogleMap>
    );
  }
}

export default class MyGreatPlace extends Component {
  static propTypes = {
    text: PropTypes.string
  };

  static defaultProps = {};

  //shouldComponentUpdate = shouldPureComponentUpdate;

  constructor(props) {
    super(props);
  }

  render() {
    return (
       <div style={greatPlaceStyle}>
          {this.props.text}
       </div>
    );
  }
}

In my index.html file, I added below javascripts. The first one is goold map api dependency. The second one is the bundle.js which is packaged by webpack. When I access my application, the google map didn't show up. I think the problem would be failed to import google map api on my component class. What is the correct way to import googleapis?

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA2sDQZ-36NLlY4iMvoiuQ7mS1n-v8iq2M" async defer></script>
    <script type="text/javascript" src="bundle.js" charset="utf-8"></script>

I implemented function which takes two callbacks success and error and check google is loaded or not. If don`t loaded it start loading used load-script for append the script node to the element in the DOM

import loadScript from 'load-script';

const HOST = 'https://maps.googleapis.com/maps/api/js';
const KEY = 'YOUR API KEY';
const URL = `${HOST}?key=${KEY}&libraries=places`;

const loadGoogleMapApi = (
  success = () => {},
  error = () => {}
) => {
  if (window.google) {
    success();
  } else {
    loadScript(URL, err => {
      const callback = err ? error : success;
      callback();
    });
  }
};

export default loadGoogleMapApi;

Then I used this function in my react component like that:

initialize() {
  this.api = L.map(this.map);
  this.markers = L.featureGroup();

  this.api.addLayer(this.markers);

  loadGoogleMapApi(() => {
    this.api.addLayer(new L.Google('ROADMAP'));
  });   
}

componentDidMount() {
  this.initialize();
  this.draw();
}

I would have left this as a comment, but I don't have commenting powers yet. Have you tried rendering the component as part of a callback from the request to Google Maps? I am wondering whether the asynchronous nature of the request is what is affecting its display.

Consider including your Google Maps like this:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>

Within your code:

let initMap = () => {
  ReactDOM.render(
    <SimpleMapPage />,
    document.getElementById('...')
  );
}

I did not see you create a new instance of the component anywhere, but I assumed that you did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM