How to Use Google Map API in a React App

Allyn Alda
5 min readJan 27, 2020

--

Are you planning to render a map in your React app but can’t get your head around the Google Map API? The NPM package, @react-google-maps/api, makes it easier to quickly render and implement map features. In this article, I will be showing you how to render Google Map in your functional component with Hooks, add clickable markers and infoWindows, dynamically show your location with a marker using geolocation, and implement a draggable marker.

These features will allow you to render markers from an array of objects with values of longitude and latitude and let your users click on the markers to open up an infoWindow that shows more details related to the particular markers. Another feature allows your users to dynamically view the marker of their current location making it incredibly easy to retrieve their longitude and latitude and then send and save this information to the database. Your users can also drag the marker to the location they prefer.

These are useful features for web apps the services of which rely heavily on geolocation such as transportation and real estate apps. I’ve used these in a simple apartment listing web project I’ve made using React and GraphQL and proved to be quite a breeze to implement.

Let’s get started

Before we can use the Google Map API you will need to create a Google Map account and generate the API key. You will need this key to get your Google Map to render in your component. Next, create a React app by typing this in your command line:

npx create-react-app google-map-app

Install the npm package in the root of the app:

npm i @react-google-maps/api

Then we are ready to go!

Rendering Google Map in your React component

Create a functional component called MapContainer.jsx in your src folder and make sure to insert this component in App.jsx so you can view the map. Import the GoogleMap and Loadscript component from @react-google-maps.

Then, replace the API key with yours and insert the code into your MapContainer component:

import React from 'react';
import { GoogleMap, LoadScript } from '@react-google-maps/api';

const MapContainer = () => {

const mapStyles = {
height: "100vh",
width: "100%"};

const defaultCenter = {
lat: 41.3851, lng: 2.1734
}

return (
<LoadScript
googleMapsApiKey='YOUR_API_KEY_HERE'>
<GoogleMap
mapContainerStyle={mapStyles}
zoom={13}
center={defaultCenter}
/>
</LoadScript>
)
}

export default MapContainer;

You will need to define the map styles since you will not be able to view the map without defining a size. You can also define default lat and lng where the map should center upon first render.

Adding clickable markers in your Google Map

How do you then place the red markers of a list of locations? Easy. You will map an array of locations containing lat and lng coordinates and render the Marker components.

import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';

export const MapContainer = () => {

const locations = [
{
name: "Location 1",
location: {
lat: 41.3954,
lng: 2.162
},
},
{
name: "Location 2",
location: {
lat: 41.3917,
lng: 2.1649
},
},
{
name: "Location 3",
location: {
lat: 41.3773,
lng: 2.1585
},
},
{
name: "Location 4",
location: {
lat: 41.3797,
lng: 2.1682
},
},
{
name: "Location 5",
location: {
lat: 41.4055,
lng: 2.1915
},
}
];

return (
...
<GoogleMap
mapContainerStyle={mapStyles}
zoom={13}
center={defaultCenter}>
{
locations.map(item => {
return (
<Marker key={item.name} position={item.location}/>
)
})
}
</GoogleMap>
)
}

Remember that the location object must have lat and lng as keys!

Adding infoWindows

Now we move on to adding clickable InfoWindows that will show your users additional information. To make this work, you will need an onSelect method in the markers component to show the details of the particular item that was clicked and use the marker’s onCloseClick to close the InfoWindow when the user clicks on the x button. You will also need to store the selected location in the component’s state. Make sure to import the InfoWindow component in the document.

import { GoogleMap, LoadScript, Marker, InfoWindow } from '@react-google-maps/api';

export const MapContainer = () => {
const [ selected, setSelected ] = useState({});

const onSelect = item => {
setSelected(item);
}
...
return (
...
{
locations.map(item => {
return (
<Marker key={item.name}
position={item.location}
onClick={() => onSelect(item)}
/>
)
})
}
{
selected.location &&
(
<InfoWindow
position={selected.location}
clickable={true}
onCloseClick={() => setSelected({})}
>
<p>{selected.name}</p>
</InfoWindow>
)
}
</GoogleMap>
)
}

Now when the user clicks on the marker, an infoWindow opens with the name of the object and an x button to close the component.

Dynamically showing marker using Geolocation API

To start, let’s get rid of the array of locations and anything related to the markers and infoWindows. This part will be focusing on rendering the map with a marker on the current location of the user. To be able to do this magic, we will be using the Geolocation API which is available through the navigator.geolocation object.

You will load a marker that will receive the location object with the lat and lng retrieved from getCurrentPosition() upon the first render of the map. This is why we’ll use this method in React.useEffect.

So in this case, we will be replacing the current location we retrieve with the defaultCenter object we have set in the previous example.

export const MapContainer = () => {

const [ currentPosition, setCurrentPosition ] = useState({});

const success = position => {
const currentPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
setCurrentPosition(currentPosition);
};

useEffect(() => {
navigator.geolocation.getCurrentPosition(success);
})
...
return (
...
<GoogleMap
mapContainerStyle={mapStyles}
zoom={13}
center={currentPosition}>
{
currentPosition.lat &&
(
<Marker position={currentPosition}
)
}
<GoogleMap/>
...
)
}

Draggable marker

Now what we want to do is allow our users to drag the marker anywhere they want if the location they want to set is not their current location. You have to make sure that you’ve set the marker to be draggable and you will also need a method that will change the marker’s location depending on where the user drags the it.

export const MapContainer = () => {
...

const onMarkerDragEnd = (e) => {
const lat = e.latLng.lat();
const lng = e.latLng.lng();
setCurrentPosition({ lat, lng})
};
...
return (
...
<GoogleMap
mapContainerStyle={mapStyles}
zoom={13}
center={currentPosition}>
{
currentPosition.lat ?
<Marker
position={currentPosition}
onDragEnd={(e) => onMarkerDragEnd(e)}
draggable={true} /> :
null
}
</GoogleMap>
...
)
}

With this feature your users will be able to set the location of their choice and you can then send this object and other details your users provides to the backend.

You can check how all of these features are used in a simple project I made to show apartments for sale in Barcelona. I fed the client side with an array of data from a server and shows all of the apartments’ location on Google Map. The users can then input the location of the apartments they want to sell by geolocation or by moving the marker. You can find the repo of this project here.

--

--

Allyn Alda

Front-End Developer based in Barcelona. Making magic with JavaScript.