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.
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, I feel it would be a good idea to list 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
- etc…
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 follow along
If you would like to code along with me, you’ll need the following:
- A React application set up
- A Google Maps API key (it’s free)
- 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:
Integrating Google Maps
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:
- Create a React component to hold the map (
Map.jsx
) - Create another React component to mark the address on the map (
LocationPin.jsx
) - 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:
- Google Map API Key
google-map-react
installed- Longitude and latitude values for your business address
Since we have all these data, we can go ahead and 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 like so:
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:
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.defaultCenter
is simply the center of the map when it loads for the first time.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
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 in the contact page. At the bottom of the file, export the Map
component like so:
export default Map
Using the Map
component
Now since 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 .
Full visibility into production React apps
Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.
LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting with metrics like client CPU load, client memory usage, and more.
The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.
Modernize how you debug your React apps — start monitoring for free.