Source: pages-sections/Feedback-Sections/FeedbackMap.js

import React, { useState, useEffect } from "react";

import { GoogleMap, useLoadScript, Marker } from "@react-google-maps/api";
import { REACT_APP_GOOGLE_MAPS_API_KEY } from "../../env";

/**
 * The `FeedbackMap` function is a React component that displays a Google Map with the ability to
 * capture user clicks and geolocation information.
 * @param props - The `FeedbackMap` component accepts props as its parameter. In the code snippet you
 * provided, the props are being destructured to extract specific properties:
 * @returns The `FeedbackMap` component is being returned. It is a functional component that renders a
 * Google Map with certain functionalities related to user interaction and location tracking. The map
 * displays a marker at a clicked location or the user's current geolocation when requested. The
 * component also includes a control button to get the user's current location.
 */
export function FeedbackMap(props) {
  const { setX = null, setY = null, ...rest } = props;
  // Google Maps States
  const [clickedLocation, setClickLocation] = useState(null);
  // static lat and lng
  const center = { lat: 1.2838566998730194, lng: 103.83347494758458 };

  const { isLoaded } = useLoadScript({
    // googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY, // Load your own API key
    googleMapsApiKey: REACT_APP_GOOGLE_MAPS_API_KEY, // Load your own API key
    libraries: ["places"],
  });

  if (!isLoaded) return <div>Loading....</div>;

  /**
   * The function `extractClickedLocation` extracts the latitude and longitude from a response object
   * and sets them as state variables.
   * @param response - The `response` parameter in the `extractClickedLocation` function is likely an
   * object containing information about a user's click event on a map. It seems to have a property
   * named `latLng` which holds the latitude and longitude coordinates of the clicked location.
   */
  const extractClickedLocation = async (response) => {
    var location = response.latLng;
    setClickLocation({ lat: location.lat(), lng: location.lng() });
    setY(location.lat());
    setX(location.lng());
    // console.log(clickedLocation);
  };

  /**
   * The function `handleGetLocationClick` retrieves the user's current geolocation coordinates using
   * the browser's geolocation API.
   */
  const handleGetLocationClick = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          setClickLocation({ lat: latitude, lng: longitude });
          setY(latitude);
          setX(longitude);
        },
        (error) => {
          console.log(error);
        }
      );
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  };

  const onMapLoad = (map) => {
    const controlDiv = document.createElement("div");
    const controlUI = document.createElement("div");
    controlUI.innerHTML = "Get Location";
    controlUI.style.backgroundColor = "white";
    controlUI.style.color = "black";
    controlUI.style.border = "2px solid #ccc";
    controlUI.style.borderRadius = "3px";
    controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
    controlUI.style.cursor = "pointer";
    controlUI.style.marginBottom = "22px";
    controlUI.style.textAlign = "center";
    controlUI.style.width = "100%";
    controlUI.style.padding = "8px 0";
    controlUI.addEventListener("click", handleGetLocationClick);
    controlDiv.appendChild(controlUI);

    const centerControl = new window.google.maps.ControlPosition(
      window.google.maps.ControlPosition.TOP_CENTER,
      0,
      10
    );

    map.controls[window.google.maps.ControlPosition.TOP_CENTER].push(
      controlDiv
    );
  };

  return (
    <GoogleMap
      zoom={11}
      center={center}
      mapContainerClassName="map"
      mapContainerStyle={{
        // width: "60%",
        height: "600px",
        // margin: "auto",
      }}
      onClick={(e) => {
        extractClickedLocation(e);
      }}
      onLoad={onMapLoad}
    >
      {clickedLocation && (
        <Marker
          position={clickedLocation}
          title={`Lat: ${clickedLocation.lat}, Lng: ${clickedLocation.lng}`}
        />
      )}
    </GoogleMap>
  );
}