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


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
      .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;

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

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

  return (

        { => (
	<li key={}>
            {} ({location.address})




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

  useEffect(() => {
    const script = document.createElement('script');
    script.src = `${googleMapsApiKey}&libraries=places`;
    script.onload = () => setLoaded(true);
  }, []);

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

function App() {
  return (
        <LocationList />


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.