Ovie Okeh Programming enthusiast, lover of all things that go beep.

Integrating Google Maps with React

5 min read 1662

Editor’s note: This post was reviewed and updated on 5 November 2021.

There’s a quote from British science-fiction writer Arthur Charles Clarke that goes, “Any sufficiently advanced technology is indistinguishable from magic.”

We might take it for granted, but Google Maps is a modern miracle in many respects. The possibilities it allows for are endless and can provide real value to your business and users. From showing your office location to showing a route a package delivery will take, Google Maps is flexible and powerful enough to handle a wide variety of use cases.

Using Google Maps in React

Indeed, there are a number of reasons why you may choose to integrate Google Maps into your React app, and we’ll be taking a look at one of the most popular ones: displaying your business address. You can then use this as a base for other, more complex cases if you desire.

Because of how incredibly powerful and complex Google Maps is, we’ll need the aptly named google-map-react package to help us integrate it into our React app. This package is a component written over a small set of the Google Maps API, and it allows you to render any React component on the Google Map. It is actively maintained and simple enough to use that it is my default go-to for integrating Google Maps in a React project.

Before we start building, however, here are some reasons why you may want to put Google Maps on your website (or web app):

  • To provide directions to your business address
  • To show a route to an event (i.e., a concert or conference)
  • To provide live updates on a shipped item’s location
  • Showcase interesting places around the world

This is just a small list of features made possible by the Google Maps API, and you may have other business requirements. For this guide, we’ll build a contact page that contains a map displaying the address of the business, as this is the most common use case I’ve encountered. The google-map-react team has provided a list of examples you can go through in case you require something a bit more advanced.

Requirements to add Google Maps to your React app

If you would like to code along with me, you’ll need the following:

  1. A React application set up
  2. A Google Maps API key (it’s free)
  3. Ten minutes of your time

I have set up a sample repository that you can clone to follow along. Run the following command to clone the repo to your local machine:

git clone https://github.com/ovieokeh/contact-page-with-google-maps.git

After cloning, run npm install to install all the project dependencies, then run npm run start to open the project in a new tab. You should see a sample contact page without Google Maps integrated. For the rest of the tutorial, we’ll create a React component to hold the Google Map and embed it into the contact page.

As for the Google Maps API key, you can get one for free by following the instructions on the Google Maps documentation. Note that you will need to set up a billing account to get rid of the limitations and watermark that comes with it.

Once you have all these ready, we can start building. The final version of what we’ll be building looks like this:

Integrate Google Maps with React How Our Finished Sample Project Should Look

Integrating Google Maps into React

To reiterate, I will not go through all the code for the contact page, as this article is focused mainly on integrating Google Map into a React project. Here are the steps we’re going to follow:

  1. Create a React component to hold the map (Map.jsx)
  2. Create another React component to mark the address on the map (LocationPin.jsx)
  3. Embed the map component into the contact page

Map.jsx

mkdir src/components/map && touch src/components/Map.jsx

Run the command above to create a new file in the /components folder. Inside this file, we’ll write the code for the map component and the address pin. Before we start writing any code, though, we have to install the google-map-react package by running the following command:

yarn add google-map-react

After installing the package, we’ll also need something else: the coordinates of our business address. This means a quick Google search for the longitude and latitude values of your business address. I’m using Google’s Amphitheatre address, so I did a quick search and got the following values:

const location = {
  address: '1600 Amphitheatre Parkway, Mountain View, california.',
  lat: 37.42216,
  lng: -122.08427,
}

The values will be different for your address, of course. Store the values in the object as shown above, and we pass these values to the Map component so we can render a pin on the map. So, to recap, you’ll need the following data:

  1. Google Map API Key
  2. google-map-react installed
  3. Longitude and latitude values for your business address

Because we have all this data, we can start building out the Map component. If you want to see the final code, you can check out the add-map branch on the repo you cloned earlier, otherwise, continue with the tutorial to learn how to build it yourself.

Still inside src/components/map/Map.jsx, import React, the google-map-package, and the corresponding CSS, like so:

import React from 'react'
import GoogleMapReact from 'google-map-react'
import './map.css'

You can get the contents of map.css from the repo here.

Create a new Map component that takes in two props:

const Map = ({ location, zoomLevel }) => (
  <div className="map">
    <h2 className="map-h2">Come Visit Us At Our Campus</h2>

    <div className="google-map">
      <GoogleMapReact
        bootstrapURLKeys={{ key: '' }}
        defaultCenter={location}
        defaultZoom={zoomLevel}
      >
        <LocationPin
          lat={location.lat}
          lng={location.lng}
          text={location.address}
        />
      </GoogleMapReact>
    </div>
  </div>
)

Can you guess what the location prop is? It’s the object we created earlier that holds the address, latitude, and longitude values of the location. zoomLevel is an integer from 0–20 that determines the scale of the map when rendered on the screen.

You’ll notice that the GoogleMapReact component takes in a child, LocationPin, but do note that it can take in any number of children. LocationPin will render the text prop on top of the map at the location we specify with the lat and lng props. We’ll create this component in the next section.

Now let’s examine the props being passed to the GoogleMapReact component to understand what each one does:

  1. bootstrapURLKeys is an object that holds the API key you copied from your Google Console. Now you can hardcode the key here, but that is not recommended for code that gets committed to GitHub or is otherwise publicly accessible. You can check out this discussion on how to secure your API keys on the client
  2. defaultCenter is simply the center of the map when it loads for the first time
  3. defaultZoom defines the initial scale of the map

This alone is enough to render a bare-bones map on the screen, but we need to do something else before we can render this component. We need to write the code for LocationPin.

LocationPin

Integrate Google Maps React Here's how to mark with LocationPin
LocationPin can mark wherever we want on the map.

We want a way to call users’ attention to a specific location on the map. Since google-map-react allows us to render any React component on the map, we can create a simple component that displays a pin icon and text.

For the icon, I’ll be using the Iconify library, which is a collection of free SVG icons. Still inside the same file we’ve been working in, import the following packages like so:

import { Icon } from '@iconify/react'
import locationIcon from '@iconify/icons-mdi/map-marker'

Then go ahead and define the LocationPin component like so:

const LocationPin = ({ text }) => (
  <div className="pin">
    <Icon icon={locationIcon} className="pin-icon" />
    <p className="pin-text">{text}</p>
  </div>
)

I’m sure this component is pretty self-explanatory. Note that the styling for LocationPin is already included in map.css, but you can style it however you like.

We’re actually done with this tutorial. All we need to do now is export the Map component and include it on the contact page. At the bottom of the file, export the Map component:

export default Map

Using the Map component

Because the Map component is just a React component, we can go ahead and use it anywhere we like. Open src/App.jsx, import the Map component, and include it between ContactSection and DisclaimerSection, like so:

import React from 'react'

import IntroSection from './components/intro/Intro'
import ContactSection from './components/contact-section/ContactSection'
import MapSection from './components/map/Map' // import the map here
import DisclaimerSection from './components/disclaimer/Disclaimer'
import FooterSection from './components/footer/Footer'

import './app.css'

const location = {
  address: '1600 Amphitheatre Parkway, Mountain View, california.',
  lat: 37.42216,
  lng: -122.08427,
} // our location object from earlier

const App = () => (
  <div className="App">
    <IntroSection />
    <ContactSection />
    <MapSection location={location} zoomLevel={17} /> {/* include it here */}
    <DisclaimerSection />
    <FooterSection />
  </div>
)

export default App

Now start the project by running yarn start in your terminal and navigate to localhost:3000. You should see your contact page with a nice-looking map that pinpoints your business address. Pretty nifty, right?

Conclusion

With fewer than 100 lines of code, we’ve been able to integrate Google Maps to display our office location along with a visual marker to pinpoint the address. This is a basic example of what you can accomplish with google-map-react.

There are more examples on their documentation for use cases that are a bit more advanced than this fairly simple one. I hope this tutorial was helpful to you, and happy coding ❤.

Get setup with LogRocket's modern React error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • ngrx middleware
    • Vuex plugin
Get started now
Ovie Okeh Programming enthusiast, lover of all things that go beep.

6 Replies to “Integrating Google Maps with React”

  1. Thanks! I followed this tutorial and was able to replicate it. Really helps alot.

    Do you have any idea on how to hide the api key? i see it in mainchunk.js

Leave a Reply