Sort a List by Driving Time with React Javascript using Google Maps API - Biz Tech

Sort a List by Driving Time with React Javascript using Google Maps API

Listen

Here is a source code example of a React component in JavaScript that retrieves and sorts a list of locations based on driving time using the Google Maps API:

import React, { useState, useEffect } from 'react';
import googleMapsApiKey from './googleMapsApiKey';

function LocationList() {
  const [locations, setLocations] = useState([]);
  const [sortedLocations, setSortedLocations] = useState([]);

  useEffect(() => {
    // Retrieve the list of locations from your backend API
    fetch('/api/locations')
      .then(response => response.json())
      .then(data => setLocations(data))
      .catch(error => console.error(error));
  }, []);

  useEffect(() => {
    if (locations.length > 0) {
      // Initialize the Google Maps client
      const gmaps = new window.google.maps.DistanceMatrixService();

      // Get the distance matrix for the starting location and destinations
      gmaps.getDistanceMatrix({
        origins: ['1600 Amphitheatre Parkway, Mountain View, CA'],
        destinations: locations.map(location => location.address),
        travelMode: 'DRIVING',
        unitSystem: window.google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false,
      }, (response, status) => {
        if (status === 'OK') {
          // Extract the driving times for each destination
          const times = response.rows[0].elements.map(element => element.duration.value);

          // Sort the destinations based on driving time
          const sorted = [...locations].sort((a, b) => times[locations.indexOf(a)] - times[locations.indexOf(b)]);
          
          setSortedLocations(sorted);
        } else {
          console.error(`Error retrieving distance matrix: ${status}`);
        }
      });
    }
  }, [locations]);

  return (
    
<div>
      
<h2>Locations</h2>

      
<ul>
        {sortedLocations.map(location => (
          
	<li key={location.id}>
            {location.name} ({location.address})
          </li>

        ))}
      </ul>

    </div>

  );
}

function GoogleMapsScriptLoader({ children }) {
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=${googleMapsApiKey}&libraries=places`;
    script.onload = () => setLoaded(true);
    document.body.appendChild(script);
  }, []);

  return loaded ? children : 
<div>Loading Google Maps...</div>
;
}

function App() {
  return (
    
<div>
      <GoogleMapsScriptLoader>
        <LocationList />
      </GoogleMapsScriptLoader>
    </div>

  );
}

export default App;

This component defines a LocationList component that retrieves a list of locations from your backend API using the fetch API. It then uses the useEffect hook to initialize the Google Maps Distance Matrix Service and calculate the driving time for each location using the getDistanceMatrix method. Once the driving times are retrieved, it sorts the locations based on driving time and updates the state with the sorted list. The component then renders the sorted list using JSX.
The component also defines a GoogleMapsScriptLoader component that loads the Google Maps JavaScript API using a script tag, and a top-level App component that wraps the LocationList component inside the GoogleMapsScriptLoader component. This ensures that the Google Maps API is loaded before the LocationList component is rendered.