In this guide, we’ll walk through the process of integrating Google Maps into a React.js application. We’ll cover the installation of necessary libraries and provide detailed coding steps for implementing various functionalities using the @react-google-maps/api library. Additionally, we’ll explore the different libraries available within @react-google-maps/api and how to install them.

Guiding steps for installing Google Maps in React JS

Step 1: Setting Up a New React App

First, let’s create a new React app using Create React App:

npx create-react-app google-maps-demo
cd google-maps-demo

Step 2: Get API Key from Google Cloud Console

  • Navigate to the “APIs & Services” > “Credentials” tab.

  • Click on “Create credentials” and select “API key”.

  • Copy the generated API key.

Step 3: Installing @react-google-maps/api

Next, install the @react-google-maps/api library along with its dependencies:

npm install @react-google-maps/api

Step 4: Set Up Google Maps Component

Create a new React component for displaying the Google Map:

import React from 'react';
import { GoogleMap, useLoadScript } from '@react-google-maps/api';
function MapComponent() {
  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: 'YOUR_API_KEY',
  });

  if (loadError) return <div>Error loading maps</div>;
  if (!isLoaded) return <div>Loading maps</div>;

  return (
    <div>
      <GoogleMap
        center={{ lat: 0, lng: 0 }}
        zoom={4}
      >
        {/* Add map markers, polygons, or other content here */}
      </GoogleMap>
    </div>
  );
}

export default MapComponent;

Replace ‘YOUR_API_KEY’ with the API key obtained from the Google Cloud Console in Step 1.

Step 5: Customize Map Features

Utilize additional features provided by @react-google-maps/api, such as markers, polygons, or drawing tools, to customize the map according to your requirements.

import React from 'react';
import { GoogleMap, Marker } from '@react-google-maps/api';

function MapComponent() {
  const mapCenter = { lat: 0, lng: 0 };
  const mapOptions = {
    zoom: 4,
    center: mapCenter,
  };

  return (
    <div>
      <GoogleMap
        mapContainerStyle={{ width: '100%', height: '400px' }}
        center={mapOptions.center}
        zoom={mapOptions.zoom}
      >
        {/* Add map markers */}
        <Marker position={{ lat: 0, lng: 0 }} />

        {/* Add polygons, drawing tools, or other content */}
      </GoogleMap>
    </div>
  );
}

export default MapComponent;

Step 6: Handle Map Events

import React from 'react';
import { GoogleMap, useMap } from '@react-google-maps/api';

function MapComponent() {
  const mapCenter = { lat: 0, lng: 0 };
  const mapOptions = {
    zoom: 4,
    center: mapCenter,
  };

  const map = useMap();

  // Example of handling map click event
  const handleMapClick = (event) => {
    console.log('Map clicked:', event.latLng.lat(), event.latLng.lng());
  };

  return (
    <div>
      <GoogleMap
        mapContainerStyle={{ width: '100%', height: '400px' }}
        center={mapOptions.center}
        zoom={mapOptions.zoom}
        onClick={handleMapClick}
        onLoad={(map) => {
          // You can access the Google Map instance here
        }}
      >
        {/* Add map markers, polygons, or other content */}
      </GoogleMap>
    </div>
  );
}

export default MapComponent;

Step 7: Implement Additional Libraries

Explore and integrate additional libraries provided by @react-google-maps/api for advanced functionalities like geocoding, directions, and places autocomplete.

useGoogleMap

const map = useGoogleMap();

useMapEvents

useMapEvents({
  onClick: (event) => {
    console.log('Map clicked', event.latLng);
  },
});

usePlacesAutocomplete

const { ready, value, suggestions: { status, data }, setValue, clearSuggestions } = usePlacesAutocomplete();

useDirectionsService

const directionsService = useDirectionsService();

useDistanceMatrixService

const distanceMatrixService = useDistanceMatrixService();

useElevationService

const elevationService = useElevationService();

useGeocode

const geolocation = useGeolocation();

useGeolocation

const geolocation = useGeolocation();

useLoadScript

const { isLoaded, loadError } = useLoadScript({
  googleMapsApiKey: 'YOUR_API_KEY',
});

useMarkerClusterer

const markerClusterer = useMarkerClusterer();

usePolygon

const polygon = usePolygon();

usePolyline

const polyline = usePolyline();

useRectangle

const rectangle = useRectangle();

useStreetViewPanorama

const streetViewPanorama = useStreetViewPanorama();

useStandaloneSearchBox

const standaloneSearchBox = useStandaloneSearchBox();

useDirectionsRenderer

const directionsRenderer = useDirectionsRenderer();

useJsApiLoader

const jsApiLoader = useJsApiLoader();

useLoadScript

const loadScript = useLoadScript();

How do the above libraries in the React Component?

import React from 'react';
import { GoogleMap, useDirectionsService, useGeocode, usePlacesAutocomplete } from '@react-google-maps/api';

const MapComponent = () => {
  // Directions Service Hook
  const { response: directionsResponse, request: directionsRequest, error: directionsError } = useDirectionsService({
    // Specify directions request parameters
  });

  // Geocode Hook
  const { response: geocodeResponse, error: geocodeError } = useGeocode({
    // Specify geocode parameters
  });

  // Places Autocomplete Hook
  const { suggestions: autocompleteSuggestions, loading: autocompleteLoading, status: autocompleteStatus, refetch: autocompleteRefetch } = usePlacesAutocomplete({
    // Specify autocomplete parameters
  });

  // Handle map click event
  const handleMapClick = (e) => {
    // Handle map click event
  };

  // Map options
  const mapOptions = {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  };

  // Render the Google Map with hooks usage
  return (
    <GoogleMap
      mapContainerStyle={{ width: '100%', height: '400px' }}
      center={mapOptions.center}
      zoom={mapOptions.zoom}
      onClick={handleMapClick}
      onLoad={(map) => {
        // You can access the Google Map instance here
      }}
    >
      {/* Add map markers, polygons, or other content */}
    </GoogleMap>
  );
};

export default MapComponent;

This code integrates the @react-google-maps/api hooks (useDirectionsService, useGeocode, usePlacesAutocomplete) within the return statement of the <GoogleMap> component. You can customize the hooks’ parameters and handle the map click event and other libraries as needed for your application.

Conclusion

By following these steps, you can seamlessly integrate Google Maps API with React.js and leverage its powerful features to create interactive and dynamic mapping solutions for your web applications. Experiment with different features and libraries to enhance the functionality and user experience of your maps.

Google Maps in React JS – FAQs

How to use Google Maps in React JS?

To use Google Maps in React.js, you can utilize the @react-google-maps/api package for easy integration.

How Google Maps initialize in React JS?

Initializing Google Maps in React.js typically involves setting up a functional component and using the GoogleMap component from the @react-google-maps/api package.

Is it possible to display multiple markers on the map using React? 

Yes, you can map through an array of marker data and render multiple markers accordingly.

Can I add event listeners to Google Maps components in React?

Yes, you can add event listeners such as onClick, onHover, etc., to interact with map elements.

How to implement autocomplete search in Google Maps with React?

You can use the usePlacesAutocomplete hook provided by @react-google-maps/api for implementing autocomplete search functionality.

Newsletter

I am a Software developer

My name is muhammad adnan and i am a professtional software developer. specialize in designing and developing efficient software applications.

Check out My Portfolio