Skip to content

Instantly share code, notes, and snippets.

@ef2k
Last active December 25, 2018 19:06
Show Gist options
  • Save ef2k/1a87796c9c3a98e0161151b152a80382 to your computer and use it in GitHub Desktop.
Save ef2k/1a87796c9c3a98e0161151b152a80382 to your computer and use it in GitHub Desktop.
Google Maps React Wrapper
/* global window, document */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
/**
* A component wrapping the Google Maps v3 API. Lazy loads the google maps
* script if not already loaded.
*/
export class GoogleMap extends Component {
constructor(props) {
super(props);
this.mapRef = React.createRef();
}
componentDidMount() {
this.loadMapScript();
}
componentWillUnmount() {
this.s.removeEventListener('load', this.handleScriptLoad);
}
loadMapScript = () => {
if (window.google) {
this.handleScriptLoad();
return;
}
const {
handleScriptLoad,
} = this;
const {
apiKey,
} = this.props;
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
const x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
this.s = s;
s.addEventListener('load', handleScriptLoad);
};
handleScriptLoad = () => {
const {
id,
options,
onLoad,
} = this.props;
const map = new window.google.maps.Map(
document.getElementById(id),
options
);
onLoad(map);
};
render() {
const {
id,
style,
} = this.props;
return (
<div className="Map">
<h1>Map</h1>
<div id={id} style={style} ref={this.mapRef} />
</div>
);
}
}
GoogleMap.propTypes = {
id: PropTypes.string,
options: PropTypes.shape(),
style: PropTypes.shape(),
onLoad: PropTypes.func,
apiKey: PropTypes.string.isRequired,
};
GoogleMap.defaultProps = {
id: 'google-map',
options: {},
style: {},
onLoad: () => {},
};
export default GoogleMap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment