VOOZH about

URL: https://blog.logrocket.com/integrating-google-maps-react/

⇱ Integrating Google Maps with React - LogRocket Blog


2024-03-14
2756
#react
Ovie Okeh
19914
👁 Image

See how LogRocket's Galileo AI surfaces the most severe issues for you

No signup required

Check it out

Editor’s note: This post was updated on 14 March 2024 by Timonwa Akintokun to discuss updates to the Google Maps API and the features they make possible in React apps, as well as to demonstrate an additional, more complex example of how to integrate Google Maps with React. Additionally, a new section was added comparing google-map-react to other, similar libraries. It was previously reviewed and updated on 5 November 2021.

👁 Integrating Google Maps In A React Project

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 that Google Maps 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.

In this tutorial, we’ll see a simple example of how to integrate Google Maps into a React project. However, we’ll start by discussing why you might want to do so and some advanced Google Maps features you can use. If you prefer, you can jump ahead to our tutorial — make sure to check out the demo project’s source code as well.

🚀 Sign up for The Replay newsletter

The Replay is a weekly newsletter for dev and engineering leaders.

Delivered once a week, it's your curated guide to the most important conversations around frontend dev, emerging AI tools, and the state of modern software.

Using Google Maps in React

There are a number of reasons why you may choose to integrate Google Maps into your React app. 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 that allows you to render any React component on a Google Map. It’s actively maintained and simple enough to use that it is my go-to for integrating Google Maps in a React project.

Before we start building, let’s discuss 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. The google-map-react team has provided a list of examples you can go through in case you require something a bit more advanced.

Additional Google Maps features for React applications

Google Maps API offers a variety of features that can enhance the functionality and user experience of React applications. Let’s explore some of these features with real-life examples of how they can be used in React applications:

  • Download maps for offline use: The ability to use maps without an internet connection is a game-changer. Popular travel apps like TripAdvisor and Citymapper have successfully integrated offline maps, allowing users to explore cities, find attractions, and navigate without needing constant connectivity. You can add this feature to a React application using the Google Maps API’s offline functionality
  • Real-time location sharing: Real-time location sharing is important for applications that provide or enable coordination and collaboration, tracking, or meetups, such as social platforms or delivery apps. Developers can use the Google Maps API to implement real-time location sharing in React applications
  • Enhanced search capabilities: Apps that focus on helping people discover things need advanced search features. For example, Airbnb uses Google Maps’ superior search capabilities to allows users to search for accommodations based on their desired location and nearby attractions. React developers can use similar tools to create an improved search experience across different applications
  • Set route options: When it comes to delivery tracking and other logistical features, it’s important to give users different route options. Using Google Maps, React applications can offer dynamic and customizable navigation options that take into account factors like traffic, distance, and delivery time. This helps users navigate efficiently and make informed decisions based on their needs
  • Measure distances: Fitness and health applications often integrate distance measurement features for users engaged in outdoor activities. React developers can harness the Google Maps API to calculate and display distances, providing valuable metrics to users
  • Get or find coordinates: Applications that use geolocations, like Geocaching and Find My iPhone, rely on getting and sharing coordinates. React apps can easily use Google Maps to get and display precise coordinates, which makes location-based features better
  • ImmersiveView for Routes: Google Maps has a new feature called Immersive View for Routes that makes trip planning easier and more fun. This feature is especially useful for people who love cycling and use fitness apps. With this feature, users can get a 3D preview of their route to help them plan their journey better. They can also get visual turn-by-turn directions and simulated conditions
  • Lens in Maps: Another innovative Google Maps feature, Lens in Maps, creates a real-time AR view of the user’s surroundings. Imagine using this feature in a travel app. When exploring a new city, users can point their device’s camera at a street and instantly view information about local businesses, restaurants, and attractions. This feature provides recommendations to users and helps them get familiar with their new environment quickly

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.

Requirements for adding 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/Timonwa/google-maps-with-react.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. In 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:

👁 Final Google Maps React Project Showing Map With Location Pin Embedded On Webpage

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 Map.jsx React component to hold the map
  2. Create a LocationPin.jsx React component to mark the address on the map
  3. Embed the map component into the contact page

The Map.jsx component

Run the command below to create a new file in the /components folder:

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

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 the coordinates of our business address. You can obtain this information with 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 of the repo you cloned earlier, otherwise, continue with the tutorial to learn how to build it yourself.

Still inside the src/components/map/Map.jsx file, 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 the map.css file from the repo.

Create a new Map component:

const Map = () => {
 return (
 <div className="map">
 <h2 className="map-h2">Come Visit Us At Our Campus</h2>
 <div className="google-map">
 <GoogleMapReact
 bootstrapURLKeys={{ key: "YOUR_API_KEY" }}
 defaultCenter={location}
 defaultZoom={17}>
 <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. The defaultZoom 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. You can hardcode the key here, but that approach 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 barebones 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 and include our address to the code.

The LocationPin component

The LocationPin component can mark wherever we want on the map:

👁 Example Of Location Pin Component Placed On 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 into the Map.jsx component like so:

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

Then go ahead and define the LocationPin component above the Map component like so:

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

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

const Map = () => {
...
};

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 "./App.css";
import IntroSection from "./components/intro/Intro";
import ContactSection from "./components/contact-section/ContactSection";
import DisclaimerSection from "./components/disclaimer/Disclaimer";
import FooterSection from "./components/footer/Footer";
import Map from "./components/map/Map";

function App() {
 return (
 <div className="App">
 <IntroSection />
 <ContactSection />
 <Map />
 <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?

Displaying multiple addresses on a Google Map

In scenarios where a business operates from multiple locations, you might want to showcase all addresses on the map. This can be done seamlessly by transforming the location from a single-object format to an array of objects, each representing a distinct address:



const location = [
 {
 address: "Address 1",
 lat: 59.955413,
 lng: 30.337844,
 },
 {
 address: "Address 2",
 lat: 59.724465,
 lng: 30.0801211,
 },
];

To showcase these multiple addresses on the map, adjust the LocationPin component to iterate through the array and display individual pins for each location:

<GoogleMapReact
 bootstrapURLKeys={{ key: "YOUR_API_KEY" }}
 defaultCenter={location[0]}
 defaultZoom={9}>
 {location.map((loc) => (
 <LocationPin lat={loc.lat} lng={loc.lng} text={loc.address} />
 ))}
</GoogleMapReact>

Introducing the key attribute within the LocationPin component ensures that each address is uniquely identified. Additionally, the defaultZoom has been adjusted to provide an optimal view that includes all listed addresses simultaneously on the screen, improving the user experience:

👁 Demo Of Displaying Multiple Addresses In A Google Map

You can view the code in the multi-address branch of the repo.

Comparison with other React Google Maps libraries

Developers have several libraries to choose from when integrating Google Maps into React applications. Let’s explore some popular alternatives:

  • react-google-maps: react-google-maps is one of the oldest and most popular alternatives, offering many features and strong community support. It’s an excellent choice for React developers who want to create interactive application mapping experiences. However, it is essential to note that the library is no longer maintained, and the last update was 6 years ago
  • react-google-maps/api: The react-google-maps/api library is said to be the rewrite of the popular react-google-maps library. It is assumably the most popular among developers and also offers a wide range of features. With its growing popularity, this library is a reliable option for developers
  • @vis.gl/react-google-maps: While @vis.gl/react-google-maps is still in its alpha phase, its popularity is steadily increasing. It also offers a wide range of features, from simple to complex, has a significant user base, and is continuously updated, making it another solid choice for developers
  • google-maps-react: Another library you might want to check is google-maps-react. Although its last update was four years ago, many developers still use it today, and it is also a good alternative

The table below should provide a helpful overview of each library and the features they offer:

google-map-react react-google-maps react-google-maps/api @vis.gl/react-google-maps google-maps-react
Weekly downloads 297,290 159,044 535,427 40,421 70,966
Last updated May 2023 January 2018 February 2024 March 2024 June 2022
Stars 6.3K 4.6K 1.7K Under 500 1.6K
Display maps
Display markers
Has autocomplete
Display clusters
Display polylines
Display polygons
Display directions
Display heat maps
Drawing tool
Different map styles
Synchronised maps

The table above clearly shows the features each npm package offers. If you are building a map that requires only basic functionalities, using google-map-react is your best bet. But if you need more complex features, you can go for @vis.gl/react-google-maps or react-google-maps/api.

While react-google-maps and google-maps-react are still being used today and have strong community support, if using a package that is still being actively maintained is crucial to you, then the other alternatives are your best options.

Conclusion

Combining Google Maps with React allows developers to add more features to their applications, such as showing addresses, tracking packages, and providing real-time updates. This partnership can improve user engagement by offering additional options, like advanced search, dynamic routes, measuring distance, and using augmented reality.

In essence, integrating Google Maps with React empowers developers to create practical and engaging applications. There are more examples in their documentation for more use cases. I hope this tutorial was helpful to you, and happy coding ❤.

Get set up 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

    $ 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>
     
  3. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • NgRx middleware
    • Vuex plugin
Get started now
👁 Image
👁 Image
👁 Image

Stop guessing about your digital experience with LogRocket

Get started for free

Recent posts:

What is TSRX?: What JSX would look like if it were designed today

TSRX adds first-class control flow, conditional hooks, and scoped styles to React via a TypeScript compiler extension — no new framework required.

👁 Image
Ikeh Akinyemi
Jun 12, 2026 ⋅ 6 min read

How to add authentication to a React Native app with Better Auth

Learn how to build a full React Native auth system using Better Auth and Expo — with email/password login, Google OAuth, session persistence, and protected routes.

👁 Image
Chinwike Maduabuchi
Jun 9, 2026 ⋅ 13 min read

AI dev tool power rankings & comparison [June 2026]

Compare the top AI development tools and models of June 2026. View updated rankings, feature breakdowns, and find the best fit for you.

👁 Image
Chizaram Ken
Jun 8, 2026 ⋅ 11 min read

How to check username availability at scale with Bloom filters

Learn how Bloom filters reduce database lookups for username availability checks while preserving correctness at scale.

👁 Image
Rosario De Chiara
Jun 8, 2026 ⋅ 6 min read
View all posts

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Sign up now