Skip to content

Instantly share code, notes, and snippets.

@jmmarco
Last active July 25, 2018 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmmarco/1d719402012b68317733ae58b392bd51 to your computer and use it in GitHub Desktop.
Save jmmarco/1d719402012b68317733ae58b392bd51 to your computer and use it in GitHub Desktop.
Google Maps with React
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Google Maps</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#root {
min-height: 100vh;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr;
font-family: Arial, Helvetica, sans-serif;
}
#map {
height: 100vh;
}
#text {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 2rem;
text-align: center;
padding: 0 10px;
}
a {
text-decoration: none;
}
</style>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
constructor(props){
super(props)
this.state = {
// no state for now..
}
// Use createRef() to create a reference to the DOM node we want
// Learn more about Refs for React here: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
this.myMapContainer = React.createRef()
}
componentDidMount() {
// Instead of using document.getElementById, use the ref we created earlier to access the element
let map = new google.maps.Map(this.myMapContainer.current, {
center: { lat: -34.9973268, lng: -58.582614 },
scrollwheel: false,
zoom: 4
});
}
render() {
return (
<div className="container">
<div ref={this.myMapContainer} id="map"></div>
<div id="text">
<p>
Google Maps now requires the use of a valid API Key.
That's why you see the popup window 'This page can't load Google Maps correctly.'
</p>
<a href="https://developers.google.com/maps/documentation/javascript/get-api-key">Go get one!</a>
</div>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('root'))
</script>
</body>
</html>
@jmmarco
Copy link
Author

jmmarco commented Jul 25, 2018

Google Maps API with React

A simple example of how to integrate the Google Maps API into your react project using Refs

🚀 to run: download zip, unzip and run using a local server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment