Location Marker on a React website using Google Maps API

Introduction

In this article, I will demonstrate how to use the custom marker on Google Maps using the Google Maps API on the React Website.

Prerequisites

  • Node version 18(LTS)
  • React 18
  • Google Cloud Account

What am I going to show in this article:

I will create a React component that renders a map using the Google Maps API, which displays a marker for a custom location. If the marker is clicked, an Info window is shown with the information about the location.

First, we need to create an API key, and then we need to enable it to use it in our application.

Navigate to https://console.cloud.google.com and sign in using the existing Gmail account or sign up with the Gmail account. After the login, kindly navigate to APIs and Services.

Navigate API and Service

Inside the APIs and Services, go to Credentials, press + Create Credentials, then choose the API key. It'll provide us with the new API key, and kindly copy it.

Credentials for APIs and Services

Then, we need to enable the Maps Javascript API. Go to API Library and choose the JS API, then enable it. If you miss this one, you'll lead to an Activation error.

Maps JavaScript Api

After that, kindly navigate to Command Prompt and Enter the following command to create a new react app.

npx create-react-app googlemapslocator

We need to delete the unnecessary files except for App.js, index.html & index.html and remove the code inside those files.

Google Map Locater

We need to install the Google Maps React package to allow us to render any React component on Google Maps.

npm install --save google-map-react

Then add the below code to the respective files.

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

App.js

import React, { useState } from "react";
import { GoogleApiWrapper, Marker, Map, InfoWindow } from "google-maps-react";

const locations = [
  {
    locationName: "@Sample Location",
    latitude: 13.251932,
    longitude: 80.240927,
    phoneNumber: "+91 99999 99999",
    availableHour: "8:00 AM - 8:00 PM",
  },
];

const LocationMap = (props) => {
  const [availableMarker, setAvailableMarker] = useState(null);
  const [selectPlace, setSelectPlace] = useState(null);
  const [showInfoWindow, setShowInfoWindow] = useState(false);

  const onMarkerClick = (props, marker, event) => {
    setAvailableMarker(marker);
    setSelectPlace(props.location);
    setShowInfoWindow(true);
  };
  const onClose = () => {
    setAvailableMarker(null);
    setSelectPlace(null);
    setShowInfoWindow(false);
  };

  return (
    <div className="map-container">
      <Map
        google={props.google}
        zoom={10}
        style={{ width: "100%", height: "100%" }}
        initialCenter={{ lat: 13.251932, lng: 80.240927 }}
      >
        {locations.slice(0, 10).map((location, index) => (
          <Marker
            key={index}
            position={{
              lat: location.latitude,
              lng: location.longitude,
            }}
            title={location.locationName}
            location={location}
            onClick={onMarkerClick}
          />
        ))}
        {selectPlace && (
          <InfoWindow
            marker={availableMarker}
            visible={showInfoWindow}
            onClose={onClose}
          >
            <div>
              <h3>{selectPlace.locationName}</h3>
              <p>Available Hours: {selectPlace.availableHour}</p>
              <p>Phone Number:{selectPlace.phoneNumber}</p>
            </div>
          </InfoWindow>
        )}
      </Map>
    </div>
  );
};

export default GoogleApiWrapper({
  apiKey: "<API-Key>",
})(LocationMap);

Now, we can go through the code step by step:

  1. Import the necessary modules and components from React and the "google-maps-react" library.
  2. Define a locations an array that contains information about a single sample location.
  3. A LocationMap a component is defined, which takes props as its parameter.
  4. Inside a component, there are state variables defined using the useState hook:
    • availableMarker: Whic keeps track of the currently selected marker.
    • selectPlace: That stores the details of the selected location when a marker is clicked.
    • showInfoWindow: To control the visibility of the Info Window.
  5. The function is allowed to respond to marker clicks. Whenever a marker is clicked, the function updates the state variables to show the Info Window with all the relevant information about the selected location.
  6. To close the InfoWindow, the function resets the state variables, causing the InfoWindow to disappear., which makes the InfoWindow disappear.
  7. Inside the return statement, the <Map> component from the "google-maps-react" library is used to render the Google Map. It specifies the initial center coordinates and zoom level.
  8. A loop is used to iterate through the locations array and render markers on the map for each location. The onMarkerClick function is passed as the onClick event handler for each marker.
  9. An <InfoWindow> component show details when a marker is clicked. It displays the selected location's name, available hours, and phone number. The InfoWindow is tied to the currently selected marker using the marker prop. The visible property determines if the InfoWindow is visible or not based on the showInfoWindow state. The onClose an event handler is triggered when the InfoWindow is closed.
  10. At last, the LocationMap component is exported after being wrapped with the GoogleApiWrapper higher-order component (HOC), which gives us the required Google Maps API functionality using the specified API key.

Maps

Note. For the map to work correctly, you must replace "<API-Key>" with a valid Google Maps API key. Additionally, ensure you have installed the required dependencies, including "react," & "google-maps-react,"

You can use any number of properties to show on the Info window.

Thanks for reading the article!