Google Map Route Optimization

import React, { useState, useEffect } from "react";
import {
  useJsApiLoader,
  GoogleMap,
  Marker,
  Autocomplete,
  DirectionsRenderer,
} from "@react-google-maps/api";

const libraries = ["places"];
const mapContainerStyle = { width: "100%", height: "100%" };
const defaultCenter = { lat: -3.745, lng: -38.523 }; // Example coordinates

function App() {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: "",
    libraries,
  });

  const [map, setMap] = useState(null);
  const [directionsResponse, setDirectionsResponse] = useState(null);
  const [distance, setDistance] = useState("");
  const [duration, setDuration] = useState("");
  const [origin, setOrigin] = useState("");
  const [destination, setDestination] = useState("");

  useEffect(() => {
    if (origin && destination) {
      getDirections();
    }
  }, [origin, destination]);

  const getDirections = async () => {
    const directionsService = new google.maps.DirectionsService();
    const results = await directionsService.route({
      origin,
      destination,
      travelMode: google.maps.TravelMode.DRIVING,
    });
    setDirectionsResponse(results);
    setDistance(results.routes[0].legs[0].distance.text);
    setDuration(results.routes[0].legs[0].duration.text);
  };

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

  return (
    <div>
      <Autocomplete onPlaceChanged={() => setOrigin(document.getElementById('origin').value)}>
        <input type="text" id="origin" placeholder="Enter origin" />
      </Autocomplete>
      <Autocomplete onPlaceChanged={() => setDestination(document.getElementById('destination').value)}>
        <input type="text" id="destination" placeholder="Enter destination" />
      </Autocomplete>
      <GoogleMap
        center={defaultCenter}
        zoom={15}
        mapContainerStyle={mapContainerStyle}
        options={{
          zoomControl: false,
          streetViewControl: false,
          mapTypeControl: false,
          fullscreenControl: false,
        }}
        onLoad={(map) => setMap(map)}
      >
        <Marker position={defaultCenter} />
        {directionsResponse && <DirectionsRenderer directions={directionsResponse} />}
      </GoogleMap>
      {distance && duration && (
        <div>
          <p>Distance: {distance}</p>
          <p>Duration: {duration}</p>
        </div>
      )}
    </div>
  );
}

export default App;

How the Real-Time Route Checking Feature Works

  • User a NPM Package: @react-google-maps/api with Google Map API KEY

  • Used Chakra UI for basic Input Box

The real-time route checking feature in your application leverages the Google Maps API to calculate and display the optimal route between two points (an origin and a destination). Here's a breakdown of how it works:

Example Workflow

  1. User selects an STS Ward No and a Destination Landfill No from the dropdown menus.

  2. The application checks if the inputs are GPS coordinates or readable addresses.

  3. If coordinates are provided, they are converted to addresses using the Google Maps Geocoding service.

  4. The Google Maps Directions Service calculates the optimal route between the two locations.

  5. The route is rendered on the map, and the distance and duration are displayed.

  6. Users can clear the route or recenter the map as needed.

Integration of Google Maps API for Real-Time Route Checking

  1. Route Calculation:

    • The calculateRoute function handles the route calculation:

      • It checks if the origin and destination inputs are non-empty.

      • It determines if the inputs are GPS coordinates or addresses.

      • For GPS coordinates, it uses the Geocoder service to convert them to addresses.

      • The DirectionsService is used to calculate the route between the origin and destination.

      • The travel mode is set to driving (google.maps.TravelMode.DRIVING).

      • The route information, including distance and duration, is stored in state variables.

  2. Route Rendering:

    • If a route is calculated, the DirectionsRenderer component displays the route on the map.

    • Directions Service and Renderer:

      • The DirectionsService is used to calculate the route between the specified origin and destination.

      • The DirectionsRenderer displays the calculated route on the map.

    • Geocoding:

      • The Geocoder service is used to convert GPS coordinates to human-readable addresses when necessary.

  3. User Interface:

    • Select components are used for selecting the STS ward number and landfill site.

    • Buttons and icons (e.g., Optimize Route, Clear Route, and pan to center) provide interactivity for calculating and clearing routes.

    • The distance and duration of the route are displayed as text elements.

Integration of Google Maps API for Real-Time Route Checking

Here are the key steps and considerations involved in integrating the Google Maps API for real-time route checking:

  1. API Key and Library Loading:

    • useJsApiLoader Hook: This hook from @react-google-maps/api is used to load the Google Maps API library and ensure it is ready before any map-related operations are performed.

    • API Key: Your Google Maps API key is passed to the hook to authenticate your requests.

  2. Map Initialization:

    • GoogleMap Component: This component renders the map and accepts various options like center coordinates, zoom level, and control options to customize the map's appearance and functionality.

  3. User Interaction:

    • Refs for Input Fields: useRef hooks are used to reference the input fields for origin and destination, allowing direct access to their current values.

    • Select Dropdowns: The dropdown menus are populated with options derived from the fetched STS and landfill data, allowing users to select their desired locations easily.

  4. Route Calculation Logic:

    • Function Definition: The calculateRoute function is defined to handle the logic of determining the route between the selected origin and destination.

    • Coordinate Check: A utility function checks if the input values are in GPS coordinate format and handles them accordingly.

    • Geocoding: If GPS coordinates are provided, they are converted to addresses using the Google Maps Geocoding service before proceeding with route calculation.

  5. Handling Directions Response:

    • Service Call: The google.maps.DirectionsService is used to request route information from the origin to the destination.

    • State Updates: The resulting directions, distance, and duration are stored in state variables using React's useState hook, enabling reactive updates to the UI.

  6. Route Clearing and Map Centering:

    • Clear Route Function: A function is provided to clear the current route, resetting the input fields and the displayed route information.

    • Pan and Zoom Controls: Users can pan and zoom the map to the initial center using an icon button that triggers map.panTo(center) and map.setZoom(15).

This architecture ensures a smooth and efficient user experience, leveraging Google Maps API to provide accurate and real-time route information.

Last updated