Monday, October 19, 2026
HomePHPCombine Google Maps in React for Actual-Time Location Monitoring

Combine Google Maps in React for Actual-Time Location Monitoring


Integrating Google Maps right into a React app is a robust location-based function. It helps for reside consumer monitoring to supply routes, geo-fencing, and real-time motion development. It is among the easiest jobs with the assistance of the Google Maps JavaScript API and React libraries.

Actual-time location monitoring improves the usability of your apps. It may be carried out for dashboards, for monitoring location on Obligation, or something that entails dynamic location-based necessities.

This React instance helps to combine Google Maps into React. It renders dynamic maps to the UI and shows markers to pinpoint the reside location. It constantly updates the consumer’s place utilizing the browser’s Geolocation API.

React Google Maps Realtime Location Tracking

Google Maps Integration steps

These are the few steps to allow required Google API providers and configure the important thing credentials with the React App. This course of builds a channel between the enduser and the Google cloud providers for which they’re registered with.

google cloud api library services

  1. Login with Google Cloud Console and create a brand new undertaking.
  2. Select APIs and Companies and allow Maps JavaScript API.
  3. Go to Credentials menu and CREATE CREDENTIALS -> API Key to generate API key.
  4. Set up React Google Maps library in your app utilizing npm set up @react-google-maps/api.
  5. Configure this key to your React app when loading React Google Maps JS library.

The credentials web page reveals the checklist of API keys generated. You possibly can limit the keys for particular domains or for utilizing explicit Google API providers.

google cloud api credential

Rendering Google Maps with present location

The TrackLocation JSX reveals HTML parts for displaying the Google Map and a location search possibility.

If the situation search just isn’t utilized, it’s exhibiting the marker on the customers present location.

react google map landing page

src/parts/TrackLocation.jsx

import { useState } from "react";
import SearchBox from "./SearchBox";
import MapContainerComponent from "./MapContainerComponent";

export default operate TrackLocation() {
  const [searchQuery, setSearchQuery] = useState("");
return (
    <div fashion={{ show: "flex" }}>
      <SearchBox onSearch={setSearchQuery} />
      <MapContainerComponent searchQuery={searchQuery} />
    </div>
  );
}

React Google Maps Element

That is the primary element which initiates the React Google Maps library by configuring the Google Cloud API service key.

It manages React states for having the Map occasion, map marker location and the searched location. The marker location is depends upon two components. It is going to be modified dynamically to point out the real-time location of the consumer. Additionally, it’s modified when the search is utilized.

With the assistance of the shopper facet Geo location capabilities, navigator.geolocation will get the latitude and longitude of the consumer’s place. Then it’s used to construct the situation object to plot the marker to the map.

src/parts/MapContainerComponent.jsx

import { useEffect, useState } from "react";
import { GoogleMap, useJsApiLoader } from "@react-google-maps/api";
import LocationMarker from "./LocationMarker";

export default operate MapContainerComponent({ searchQuery }) {
  const [map, setMap] = useState(null);
  const [userLocation, setUserLocation] = useState(null);
  const [searchLocation, setSearchLocation] = useState(null);

  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: "YOUR API KEY",
    libraries: ["places"],
  });

  useEffect(() => {
    if (navigator.geolocation) {
      const watchId = navigator.geolocation.watchPosition(
        (pos) => {
          const newLoc = {
            lat: pos.coords.latitude,
            lng: pos.coords.longitude,
          };
          setUserLocation(newLoc);
          if (map && !searchLocation) {
            map.setCenter(newLoc);
            map.setZoom(13);
          }
        },
        (err) => console.error("Location error:", err),
        { enableHighAccuracy: true, maximumAge: 1000 }
      );
      return () => navigator.geolocation.clearWatch(watchId);
    } else {
      console.error("Geolocation not supported");
    }
  }, [map, searchLocation]);

  useEffect(() => {
    if (!searchQuery || !window.google || !map) return;
    const geocoder = new window.google.maps.Geocoder();
    geocoder.geocode({ deal with: searchQuery }, (outcomes, standing) => {
      if (standing === "OK" && outcomes[0]) {
        const loc = outcomes[0].geometry.location;
        const newSearchLoc = { lat: loc.lat(), lng: loc.lng() };
        setSearchLocation(newSearchLoc);
        if (userLocation) {
          const bounds = new window.google.maps.LatLngBounds();
          bounds.prolong(userLocation);
          bounds.prolong(newSearchLoc);
          map.fitBounds(bounds);
        } else {
          map.setCenter(newSearchLoc);
          map.setZoom(12);
        }
      } else {
        console.warn("Location not discovered for:", searchQuery);
      }
    });
  }, [searchQuery, map, userLocation]);

  const zoomToLocation = (loc) => ;

  return (
    <div className="map-container">
      {isLoaded && (
        <GoogleMap
          mapContainerStyle={{ width: "100%", top: "100vh" }}
          heart={userLocation || { lat: 20.5937, lng: 78.9629 }}
          zoom={userLocation ? 13 : 5}
          onLoad={setMap}
          choices={{
            streetViewControl: false,
            mapTypeControl: false,
            fullscreenControl: false,
          }}>
          <LocationMarker
            place={userLocation}
            title="Your Location"
            onClick={() => zoomToLocation(userLocation)}
          />
          <LocationMarker
            place={searchLocation}
            title="Tracked Location"
            onClick={() => zoomToLocation(searchLocation)}
          />
        </GoogleMap>
      )}
      {userLocation && (
        <button
          className="floating-btn"
          onClick={() => zoomToLocation(userLocation)}>
           My Location
        </button>
      )}
    </div>
  );
}

This LocationMarker element is a part of the primary React element that accepts the customers location or searched location. It pins the marker to the Map based mostly on the situation particulars.

src/parts/LocationMarker.js

import React from "react";
import { Marker } from "@react-google-maps/api";

export default operate LocationMarker({ place, title, onClick }) {
  return place ? <Marker place={place} title={title} onClick={onClick} /> : null;
}

Google Maps Search function

The search kind accommodates interface to enter the place to mark on the Map. When the search is utilized, the LocationMarker rendered with the place:searchLocation reveals the marker on the suitable place.

src/parts/SearchBox.jsx

import { useState } from "react";

export default operate SearchBox({ onSearch }) {
  const [query, setQuery] = useState("");
  const handleSubmit = (e) => {
    e.preventDefault();
    if (question.trim()) onSearch(question);
  };

 return (
    <div className="search-sidebar">
      <h3 className="sidebar-title">Observe Location</h3>
      <kind onSubmit={handleSubmit}>
        <enter
          sort="textual content"
          placeholder="Enter a spot"
          worth={question}
          onChange={(e) => setQuery(e.goal.worth)}
          className="search-input"
        />
        <button sort="submit" className="search-btn">
          Search
        </button>
      </kind>
    </div>
  );
}

Conclusion

Actual-time location monitoring in React turns into straightforward with the joint capabilities of the Geolocation API and Google Maps. It adjustments the consumer’s place on motion. This instance enriches consumer expertise with a reside motion monitoring function. And, will probably be straightforward to make use of in a location-based React utility that should render customers’ reside areas.

References:

  1. React Google Maps API wrapper.
  2. Google Maps rendering greatest practices.

Obtain

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments