routes-route-matrix

Sample code supporting Google Maps Platform JavaScript API documentation. author(s): Geo Developer IX Documentation Team

HTML

<!doctype html>
<!--
 @license
 Copyright 2025 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->

<html>
  <head>
    <title>Route matrix</title>

    <script>
      // prettier-ignore
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
            });
    </script>
  </head>
  <body>
    <div id="container">
      <div id="map"></div>
      <div id="sidebar">
        <h3 style="flex-grow: 0">Request</h3>
        <pre style="flex-grow: 1" id="request"></pre>
        <h3 style="flex-grow: 0">Response</h3>
        <pre style="flex-grow: 1" id="response"></pre>
      </div>
    </div>
  </body>
</html>

CSS

/*
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

/*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */
/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#container {
  height: 100%;
  display: flex;
}

#sidebar {
  flex-basis: 15rem;
  flex-grow: 1;
  padding: 1rem;
  max-width: 30rem;
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
}

#map {
  flex-basis: 0;
  flex-grow: 4;
  height: 100%;
}

#sidebar {
  flex-direction: column;
}

JavaScript

'use strict';
/*
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

// Initialize and add the map.
let map;
const markers = [];
const center = { lat: 51.55, lng: -1.8 };

async function init() {
  //  Request the needed libraries.
  const [
    { Map },
    { Place },
    { AdvancedMarkerElement, PinElement },
    { RouteMatrix },
    { LatLngBounds, UnitSystem },
  ] = await Promise.all([
    google.maps.importLibrary('maps'),
    google.maps.importLibrary('places'),
    google.maps.importLibrary('marker'),
    google.maps.importLibrary('routes'),
    google.maps.importLibrary('core'),
  ]);

  const bounds = new LatLngBounds();

  map = new Map(document.getElementById('map'), {
    zoom: 8,
    center,
    mapId: 'DEMO_MAP_ID',
  });

  // Build the request using Place instances.
  const origin1 = new Place({
    id: 'ChIJ83WZp86p2EcRbMrkYqGncBQ', // Greenwich, London, UK
  });
  const origin2 = new Place({
    id: 'ChIJCSkVvleJc0gR8HHaTGpajKc', // Southampton, UK
  });
  const destinationA = new Place({
    id: 'ChIJYdizgWaDcUgRH9eaSy6y5I4', // Bristol, UK
  });
  const destinationB = new Place({
    id: 'ChIJ9VPsNNQCbkgRDmeGZdsGNBQ', // Cardiff, UK
  });

  await Promise.all([
    origin1.fetchFields({ fields: ['location', 'displayName'] }),
    origin2.fetchFields({ fields: ['location', 'displayName'] }),
    destinationA.fetchFields({ fields: ['location', 'displayName'] }),
    destinationB.fetchFields({ fields: ['location', 'displayName'] }),
  ]);

  const destinations = [destinationA, destinationB];
  const origins = [origin1, origin2];
  const request = {
    origins,
    destinations,
    travelMode: 'DRIVING',
    units: UnitSystem.METRIC,
    fields: ['distanceMeters', 'durationMillis', 'condition'],
  };

  // Show the request.
  document.getElementById('request').innerText = JSON.stringify(
    request,
    null,
    2
  );

  // Get the RouteMatrix response.
  const response = await...