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;
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;
/* 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;}
Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-20 UTC."],[[["\u003cp\u003eThis example showcases the use of the \u003ccode\u003eDistanceMatrixService\u003c/code\u003e to calculate and display distances between multiple locations.\u003c/p\u003e\n"],["\u003cp\u003eIt utilizes the Google Maps JavaScript API to retrieve distances and display them on a map.\u003c/p\u003e\n"],["\u003cp\u003eThe sample code demonstrates how to make a request to the Distance Matrix service and handle the response.\u003c/p\u003e\n"],["\u003cp\u003eIt provides both TypeScript and JavaScript code snippets for implementation.\u003c/p\u003e\n"],["\u003cp\u003eUsers can interact with the example through JSFiddle or Google Cloud Shell, and can clone the sample code for local execution.\u003c/p\u003e\n"]]],["The code initializes a `DistanceMatrixService` to calculate distances between locations. It defines two origins (one coordinate pair and one address) and two destinations (one address and one coordinate pair). A request is built with these points and driving mode, then submitted to the service. The response is displayed, and a geocoder determines the location of origins/destinations to add markers to the map and delete the markers if needed. The request and response are displayed in HTML as text.\n"],null,["This example demonstrates the use of the `DistanceMatrixService` object to fetch\nthe distances between a set of locations.\n\nRead the [documentation](/maps/documentation/javascript/distancematrix). \n\nTypeScript \n\n```typescript\nfunction initMap(): void {\n const bounds = new google.maps.LatLngBounds();\n const markersArray: google.maps.Marker[] = [];\n\n const map = new google.maps.Map(\n document.getElementById(\"map\") as HTMLElement,\n {\n center: { lat: 55.53, lng: 9.4 },\n zoom: 10,\n }\n );\n\n // initialize services\n const geocoder = new google.maps.Geocoder();\n const service = new google.maps.DistanceMatrixService();\n\n // build request\n const origin1 = { lat: 55.93, lng: -3.118 };\n const origin2 = \"Greenwich, England\";\n const destinationA = \"Stockholm, Sweden\";\n const destinationB = { lat: 50.087, lng: 14.421 };\n\n const request = {\n origins: [origin1, origin2],\n destinations: [destinationA, destinationB],\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.METRIC,\n avoidHighways: false,\n avoidTolls: false,\n };\n\n // put request on page\n (document.getElementById(\"request\") as HTMLDivElement).innerText =\n JSON.stringify(request, null, 2);\n\n // get distance matrix response\n service.getDistanceMatrix(request).then((response) =\u003e {\n // put response\n (document.getElementById(\"response\") as HTMLDivElement).innerText =\n JSON.stringify(response, null, 2);\n\n // show on map\n const originList = response.originAddresses;\n const destinationList = response.destinationAddresses;\n\n deleteMarkers(markersArray);\n\n const showGeocodedAddressOnMap = (asDestination: boolean) =\u003e {\n const handler = ({ results }: google.maps.GeocoderResponse) =\u003e {\n map.fitBounds(bounds.extend(results[0].geometry.location));\n markersArray.push(\n new google.maps.Marker({\n map,\n position: results[0].geometry.location,\n label: asDestination ? \"D\" : \"O\",\n })\n );\n };\n\n return handler;\n };\n\n for (let i = 0; i \u003c originList.length; i++) {\n const results = response.rows[i].elements;\n\n geocoder\n .geocode({ address: originList[i] })\n .then(showGeocodedAddressOnMap(false));\n\n for (let j = 0; j \u003c results.length; j++) {\n geocoder\n .geocode({ address: destinationList[j] })\n .then(showGeocodedAddressOnMap(true));\n }\n }\n });\n}\n\nfunction deleteMarkers(markersArray: google.maps.Marker[]) {\n for (let i = 0; i \u003c markersArray.length; i++) {\n markersArray[i].setMap(null);\n }\n\n markersArray = [];\n}\n\ndeclare global {\n interface Window {\n initMap: () =\u003e void;\n }\n}\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/distance-matrix/index.ts#L10-L101\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nfunction initMap() {\n const bounds = new google.maps.LatLngBounds();\n const markersArray = [];\n const map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: 55.53, lng: 9.4 },\n zoom: 10,\n });\n // initialize services\n const geocoder = new google.maps.Geocoder();\n const service = new google.maps.DistanceMatrixService();\n // build request\n const origin1 = { lat: 55.93, lng: -3.118 };\n const origin2 = \"Greenwich, England\";\n const destinationA = \"Stockholm, Sweden\";\n const destinationB = { lat: 50.087, lng: 14.421 };\n const request = {\n origins: [origin1, origin2],\n destinations: [destinationA, destinationB],\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.METRIC,\n avoidHighways: false,\n avoidTolls: false,\n };\n\n // put request on page\n document.getElementById(\"request\").innerText = JSON.stringify(\n request,\n null,\n 2,\n );\n // get distance matrix response\n service.getDistanceMatrix(request).then((response) =\u003e {\n // put response\n document.getElementById(\"response\").innerText = JSON.stringify(\n response,\n null,\n 2,\n );\n\n // show on map\n const originList = response.originAddresses;\n const destinationList = response.destinationAddresses;\n\n deleteMarkers(markersArray);\n\n const showGeocodedAddressOnMap = (asDestination) =\u003e {\n const handler = ({ results }) =\u003e {\n map.fitBounds(bounds.extend(results[0].geometry.location));\n markersArray.push(\n new google.maps.Marker({\n map,\n position: results[0].geometry.location,\n label: asDestination ? \"D\" : \"O\",\n }),\n );\n };\n return handler;\n };\n\n for (let i = 0; i \u003c originList.length; i++) {\n const results = response.rows[i].elements;\n\n geocoder\n .geocode({ address: originList[i] })\n .then(showGeocodedAddressOnMap(false));\n\n for (let j = 0; j \u003c results.length; j++) {\n geocoder\n .geocode({ address: destinationList[j] })\n .then(showGeocodedAddressOnMap(true));\n }\n }\n });\n}\n\nfunction deleteMarkers(markersArray) {\n for (let i = 0; i \u003c markersArray.length; i++) {\n markersArray[i].setMap(null);\n }\n\n markersArray = [];\n}\n\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/distance-matrix/docs/index.js#L8-L91\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n\nCSS \n\n```css\n/* Optional: Makes the sample page fill the window. */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\n#container {\n height: 100%;\n display: flex;\n}\n\n#sidebar {\n flex-basis: 15rem;\n flex-grow: 1;\n padding: 1rem;\n max-width: 30rem;\n height: 100%;\n box-sizing: border-box;\n overflow: auto;\n}\n\n#map {\n flex-basis: 0;\n flex-grow: 4;\n height: 100%;\n}\n\n#sidebar {\n flex-direction: column;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/distance-matrix/docs/style.css#L7-L39\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eDistance Matrix Service\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cdiv id=\"container\"\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n \u003cdiv id=\"sidebar\"\u003e\n \u003ch3 style=\"flex-grow: 0\"\u003eRequest\u003c/h3\u003e\n \u003cpre style=\"flex-grow: 1\" id=\"request\"\u003e\u003c/pre\u003e\n \u003ch3 style=\"flex-grow: 0\"\u003eResponse\u003c/h3\u003e\n \u003cpre style=\"flex-grow: 1\" id=\"response\"\u003e\u003c/pre\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n\n \u003c!-- \n The `defer` attribute causes the script to execute after the full HTML\n document has been parsed. For non-blocking uses, avoiding race conditions,\n and consistent behavior across browsers, consider loading using Promises. See\n https://developers.google.com/maps/documentation/javascript/load-maps-js-api\n for more information.\n --\u003e\n \u003cscript\n src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly\"\n defer\n \u003e\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/distance-matrix/docs/index.html#L8-L38\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/distance-matrix/jsfiddle) [Google Cloud Shell](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgooglemaps%2Fjs-samples&cloudshell_git_branch=sample-distance-matrix&cloudshell_tutorial=cloud_shell_instructions.md&cloudshell_workspace=.)\n\nClone Sample\n\n\nGit and Node.js are required to run this sample locally. Follow these [instructions](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to install Node.js and NPM. The following commands clone, install dependencies and start the sample application. \n\n git clone -b sample-distance-matrix https://github.com/googlemaps/js-samples.git\n cd js-samples\n npm i\n npm start\n\n\nOther samples can be tried by switching to any branch beginning with `sample-`\u003cvar translate=\"no\"\u003eSAMPLE_NAME\u003c/var\u003e. \n\n git checkout sample-\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-nx\"\u003eSAMPLE_NAME\u003c/span\u003e\u003c/var\u003e\n npm i\n npm start"]]