Distance Matrix Service Stay organized with collections Save and categorize content based on your preferences.
Page Summary
This example showcases the use of the
DistanceMatrixServiceto calculate and display distances between multiple locations.It utilizes the Google Maps JavaScript API to retrieve distances and display them on a map.
The sample code demonstrates how to make a request to the Distance Matrix service and handle the response.
It provides both TypeScript and JavaScript code snippets for implementation.
Users can interact with the example through JSFiddle or Google Cloud Shell, and can clone the sample code for local execution.
This example demonstrates the use of theDistanceMatrixService object to fetchthe distances between a set of locations.
Read thedocumentation.
TypeScript
functioninitMap():void{constbounds=newgoogle.maps.LatLngBounds();constmarkersArray:google.maps.Marker[]=[];constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{center:{lat:55.53,lng:9.4},zoom:10,});// initialize servicesconstgeocoder=newgoogle.maps.Geocoder();constservice=newgoogle.maps.DistanceMatrixService();// build requestconstorigin1={lat:55.93,lng:-3.118};constorigin2="Greenwich, England";constdestinationA="Stockholm, Sweden";constdestinationB={lat:50.087,lng:14.421};constrequest={origins:[origin1,origin2],destinations:[destinationA,destinationB],travelMode:google.maps.TravelMode.DRIVING,unitSystem:google.maps.UnitSystem.METRIC,avoidHighways:false,avoidTolls:false,};// put request on page(document.getElementById("request")asHTMLDivElement).innerText=JSON.stringify(request,null,2);// get distance matrix responseservice.getDistanceMatrix(request).then((response)=>{// put response(document.getElementById("response")asHTMLDivElement).innerText=JSON.stringify(response,null,2);// show on mapconstoriginList=response.originAddresses;constdestinationList=response.destinationAddresses;deleteMarkers(markersArray);constshowGeocodedAddressOnMap=(asDestination:boolean)=>{consthandler=({results}:google.maps.GeocoderResponse)=>{map.fitBounds(bounds.extend(results[0].geometry.location));markersArray.push(newgoogle.maps.Marker({map,position:results[0].geometry.location,label:asDestination?"D":"O",}));};returnhandler;};for(leti=0;i <originList.length;i++){constresults=response.rows[i].elements;geocoder.geocode({address:originList[i]}).then(showGeocodedAddressOnMap(false));for(letj=0;j <results.length;j++){geocoder.geocode({address:destinationList[j]}).then(showGeocodedAddressOnMap(true));}}});}functiondeleteMarkers(markersArray:google.maps.Marker[]){for(leti=0;i <markersArray.length;i++){markersArray[i].setMap(null);}markersArray=[];}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
JavaScript
functioninitMap(){constbounds=newgoogle.maps.LatLngBounds();constmarkersArray=[];constmap=newgoogle.maps.Map(document.getElementById("map"),{center:{lat:55.53,lng:9.4},zoom:10,});// initialize servicesconstgeocoder=newgoogle.maps.Geocoder();constservice=newgoogle.maps.DistanceMatrixService();// build requestconstorigin1={lat:55.93,lng:-3.118};constorigin2="Greenwich, England";constdestinationA="Stockholm, Sweden";constdestinationB={lat:50.087,lng:14.421};constrequest={origins:[origin1,origin2],destinations:[destinationA,destinationB],travelMode:google.maps.TravelMode.DRIVING,unitSystem:google.maps.UnitSystem.METRIC,avoidHighways:false,avoidTolls:false,};// put request on pagedocument.getElementById("request").innerText=JSON.stringify(request,null,2,);// get distance matrix responseservice.getDistanceMatrix(request).then((response)=>{// put responsedocument.getElementById("response").innerText=JSON.stringify(response,null,2,);// show on mapconstoriginList=response.originAddresses;constdestinationList=response.destinationAddresses;deleteMarkers(markersArray);constshowGeocodedAddressOnMap=(asDestination)=>{consthandler=({results})=>{map.fitBounds(bounds.extend(results[0].geometry.location));markersArray.push(newgoogle.maps.Marker({map,position:results[0].geometry.location,label:asDestination?"D":"O",}),);};returnhandler;};for(leti=0;i <originList.length;i++){constresults=response.rows[i].elements;geocoder.geocode({address:originList[i]}).then(showGeocodedAddressOnMap(false));for(letj=0;j <results.length;j++){geocoder.geocode({address:destinationList[j]}).then(showGeocodedAddressOnMap(true));}}});}functiondeleteMarkers(markersArray){for(leti=0;i <markersArray.length;i++){markersArray[i].setMap(null);}markersArray=[];}window.initMap=initMap;
CSS
/* 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;}
HTML
<html> <head> <title>Distance Matrix Service</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div> <div></div> <div> <h3>Request</h3> <pre></pre> <h3>Response</h3> <pre></pre> </div> </div> <!-- The `defer` attribute causes the script to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></script> </body></html>
Try Sample
Clone Sample
Git and Node.js are required to run this sample locally. Follow theseinstructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.
gitclone-bsample-distance-matrixhttps://github.com/googlemaps/js-samples.gitcdjs-samplesnpminpmstart
Other samples can be tried by switching to any branch beginning withsample-SAMPLE_NAME.
gitcheckoutsample-SAMPLE_NAMEnpminpmstart
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-11 UTC.