Skip to content

Instantly share code, notes, and snippets.

@csandman
Last active May 28, 2019 16:20
Show Gist options
  • Save csandman/d8796a9844c1c23a495bc35578d1384b to your computer and use it in GitHub Desktop.
Save csandman/d8796a9844c1c23a495bc35578d1384b to your computer and use it in GitHub Desktop.
A bare-bones React component for using the Google Maps API
// takes props:
// apiKey: string
// mapOptions: object
// mapID: string
// onMapLoad: function(mapOject)
// mapLibraries: array[string]
// Function Version
import React, { useEffect, useCallback } from "react";
const GoogleMap = props => {
const onScriptLoad = () => {
const map = new window.google.maps.Map(
document.getElementById(props.mapID),
props.mapOptions
);
props.onMapLoad(map);
};
useEffect(() => {
if (window.google) {
onScriptLoad();
} else {
let loadScript = document.createElement("script");
loadScript.type = "text/javascript";
loadScript.src = `https://maps.google.com/maps/api/js?key=${
props.apiKey
}${
props.mapLibraries.length
? `&libraries=${props.mapLibraries.join(",")}`
: ""
}`;
var x = document.getElementsByTagName("script")[0];
x.parentNode.insertBefore(loadScript, x);
loadScript.addEventListener("load", e => {
onScriptLoad();
});
}
}, []);
return <div id={props.mapID} />;
}
export default props => useCallback(<GoogleMap {...props} />, []);
// Component Version
import React, { Component } from "react";
class GoogleMap extends Component {
componentDidMount() {
if (window.google) {
this.onScriptLoad();
} else {
let loadScript = document.createElement("script");
loadScript.type = "text/javascript";
loadScript.src = `https://maps.google.com/maps/api/js?key=${
this.props.apiKey
}${
this.props.mapLibraries.length
? `&libraries=${this.props.mapLibraries.join(",")}`
: ""
}`;
var x = document.getElementsByTagName("script")[0];
x.parentNode.insertBefore(loadScript, x);
loadScript.addEventListener("load", e => {
this.onScriptLoad();
});
}
}
onScriptLoad = () => {
const map = new window.google.maps.Map(
document.getElementById(this.props.mapID),
this.props.mapOptions
);
this.props.onMapLoad(map);
};
render() {
return <div id={this.props.mapID} />;
}
}
export default React.memo(GoogleMap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment