Google Maps in React
So you are working on your React project and you want to integrate Google Maps. That can be a task easier said than done, but with the GMaps NPM package for React and a call to Google’s geocode API it can be a rather simple process. This tutorial was made with the expectation that you are using webpack and have that development environment set up. If not, I recommend using the boilerplate found here. Credit goes to Colin for creating this repository.
The first thing you will need to do is get an API key for google maps. You can get those credential here Next, install react-gmaps packages from NPM in your command line.
The next thing you need to do is import your components from the react-gmaps package. We will import the components using curly brackets. The component has four individual components that we can use in our example. The GMaps component is the main component which renders the Google map. The Marker will be nested within the GMaps component to create a marker on the map. The Infowindow creates an info window that can label a location on the map. Circle creates a circle around the location on the map. See the code snippet below.
Make sure you enter your API key into the GMaps component. When the page loads, the componentWillMount function will run before the component is mounted or rendered. This piece of code will get your current geolocation from the browser, update the state with that location, and will re-render the map. The form we created will takes in any address and will use fetch to send an API call to Google’s geocode API. This will return the longitude and latitude of the searched address and we’ll use that result to update our state.. And that’s it, you are able to create a dynamic map with a few lines of code.