How to add Google Maps in React using the package

In this article, you will learn how to add Google Maps in React using the @googlemaps/js-api-loader package. The package allows you to load the Google Maps JavaScript API asynchronously, making it easier to add maps to your React applications.

You will learn how to install and use the package, create a simple Google Maps component, and add marker to the map. By the end of the article, you will have a working Google Map in your React application.

Demo Application

Output - How to add Google Maps in React using the package - Clue Mediator
Output – How to add Google Maps in React using the package – Clue Mediator

How to add Google Maps in React using the package

  1. Project structure
  2. Package dependencies
  3. Implementation
  4. Output

1. Project structure

  • add-google-maps-react
    • node_modules
    • public
      • index.html
    • src
      • App.js
      • GMap.js
      • index.css
      • index.js
    • package-lock.json
    • package.json
    • README.md

2. Package dependencies

Run the following command to install @googlemaps/js-api-loader npm package in your project directory.

You will find the version of the following packages in React application.

react
^18.2.0
@googlemaps/js-api-loader
^1.15.1

3. Implementation

Create a new component to render the map. You can use the useEffect hook to load the Google Maps API and initialize the map.

GMap.js
App.js

In this example, the Loader object is used to load the Google Maps API with the required options, such as the API key and the libraries to use. Once the API is loaded, the map variable is initialized with the google.maps.Map constructor and set as the state of the component using the setMap function. Finally, the map variable is rendered inside a div element.

index.js

4. Output

Run your application and check the output in the browser.
Live Demo

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *