Zhao Yi Zhao Yi - 2 months ago 44
Javascript Question

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>

Answer

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.

Comments