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
How to add Google Maps in React using the package
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.
npm i @googlemaps/js-api-loader
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
import React, { useEffect, useRef, useState } from 'react';
const GMap = () => {
const googleMapRef = useRef(null);
const [map, setMap] = useState(null);
useEffect(() => {
const googleMap = initGoogleMap();
setMap(googleMap);
}, []);
useEffect(() => {
if (!map) return;
new window.google.maps.Marker({
position: { lat: -34.397, lng: 150.644 },
map: map
});
}, [map])
const initGoogleMap = () => {
return new window.google.maps.Map(googleMapRef.current, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
return <div 500="" ref={googleMapRef} style={{ width: 600, height: }}>
}
export default GMap;</div>
App.js
import React, { useState, useEffect } from 'react';
import { Loader } from '@googlemaps/js-api-loader';
import GMap from './GMap';
// API key of the google map
const GOOGLE_MAP_API_KEY = '<your_google_map_api_key>';
const App = () => {
const [loadMap, setLoadMap] = useState(false);
useEffect(() => {
const options = {
apiKey: GOOGLE_MAP_API_KEY,
version: "weekly",
libraries: ['geometry']
};
new Loader(options).load().then(() => {
setLoadMap(true);
}).catch(e => {
console.error('Sorry, something went wrong: Please try again later. Error:', e);
});
}, []);
return (
<div class="App">
<h4>How to add Google Maps in React using the package - <a href="https://www.cluemediator.com">Clue Mediator</a></h4>
{!loadMap ? <div>Loading...</div> : <gmap>}
<br>
<small><b>Note:</b> In order to make it work, you have to set the YOUR_GOOGLE_MAP_API_KEY in App.js file. </small>
</gmap></div>
);
}
export default App;
</your_google_map_api_key>
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
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<app>
);
</app>
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..!!