Distance Matrix Service Stay organized with collections Save and categorize content based on your preferences.
This page describes the client-side service available with the Maps JavaScript API. If you want to work with Google Maps web services on your server, take a look at theNode.js Client for Google Maps Services. The page at that link also introduces the Java Client, Python Client and Go Client for Google Maps Services.
Overview
Also see the Maps JavaScript API Reference:Distance MatrixGoogle's Distance Matrix service computes travel distance and journey duration between multiple origins and destinations using a given mode of travel.
This service does not return detailed route information. Route information, including polylines and textual directions, can be obtained by passing the desired single origin and destination to theDirections Service.
Getting started
Before using the Distance Matrix service in the Maps JavaScript API, first ensure that the Distance Matrix API (Legacy) is enabled in the Google Cloud console, in the same project you set up for the Maps JavaScript API.
To view your list of enabled APIs:
- Go to the Google Cloud console.
- Click theSelect a project button, then select the same project you set up for the Maps JavaScript API and clickOpen.
- From the list of APIs on theDashboard, look forDistance Matrix API (Legacy).
- If you see the API in the list, you're all set. If the API is not listed, enable it athttps://console.cloud.google.com/apis/library/distance-matrix-backend.googleapis.com
Pricing and policies
Pricing
To learn about pricing and usage policies for the JavaScript Distance Matrix service, seeUsage and Billingfor the Distance Matrix API (Legacy).
Note: Each query sent to the Distance Matrix service is limitedby the number of allowed elements, where the number oforigins times thenumber ofdestinations defines the number of elements.
Policies
Use of the Distance Matrix service must be in accordance with thepolicies described for the Distance Matrix API (Legacy).
Distance Matrix Requests
Accessing the Distance Matrix service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass acallback method to execute upon completion of the request, to process the results.
You access the Distance Matrix service within your code via thegoogle.maps.DistanceMatrixService constructor object. TheDistanceMatrixService.getDistanceMatrix() method initiates a request to the Distance Matrix service, passing it aDistanceMatrixRequest object literal containing the origins, destinations, and travel mode, as well as a callback method to execute upon receipt of the response.
varorigin1=newgoogle.maps.LatLng(55.930385,-3.118425);varorigin2='Greenwich, England';vardestinationA='Stockholm, Sweden';vardestinationB=newgoogle.maps.LatLng(50.087692,14.421150);varservice=newgoogle.maps.DistanceMatrixService();service.getDistanceMatrix({origins:[origin1,origin2],destinations:[destinationA,destinationB],travelMode:'DRIVING',transitOptions:TransitOptions,drivingOptions:DrivingOptions,unitSystem:UnitSystem,avoidHighways:Boolean,avoidTolls:Boolean,},callback);functioncallback(response,status){// SeeParsing the Results for// the basics of a callback function.}
TheDistanceMatrixRequest contains the following fields:
origins(required) — An array containing one or more address strings,google.maps.LatLngobjects, orPlace objects from which to calculate distance and time.destinations(required) — An array containing one or more address strings,google.maps.LatLngobjects, orPlace objects to which to calculate distance and time.travelMode(optional) — The mode of transport to use when calculating directions. See the section ontravel modes.transitOptions(optional) — Options that apply only to requests wheretravelModeisTRANSIT. Valid values are described in the section ontransit options.drivingOptions(optional) specifies values that apply only to requests wheretravelModeisDRIVING. Valid values are described in the section onDriving Options.unitSystem(optional) — The unit system to use when displaying distance. Accepted values are:google.maps.UnitSystem.METRIC(default)google.maps.UnitSystem.IMPERIAL
avoidHighways(optional) — Iftrue, the routes between origins and destinations will be calculated to avoid highways where possible.avoidTolls(optional) — Iftrue, the directions between points will be calculated using non-toll routes, wherever possible.
durationInTraffic field is nowdeprecated. It was previously the recommended way for Google Maps Platform Premium Plan customers to specify whether the result should include a duration that takes into account current traffic conditions. You should now use thedrivingOptions field instead.Travel Modes
When calculating times and distances, you can specify which transportation mode to use. The following travel modes are currently supported:
BICYCLINGrequests bicycling directions via bicycle paths & preferred streets (currently only available in the US and some Canadian cities).DRIVING(default) indicates standard driving directions using the road network.TRANSITrequests directions via public transit routes. This option may only be specified if the request includes an API key. See the section ontransit options for the available options in this type of request.WALKINGrequests walking directions via pedestrian paths & sidewalks (where available).
Transit Options
The Transit Service is currently 'experimental'. During this phase, we will be implementing rate limits to prevent API abuse. We will eventually enforce a cap on total queries per map load based on fair usage of the API.
The available options for a distance matrix request vary across travel modes. In transit requests, theavoidHighways andavoidTolls options are ignored. You can specify transit-specific routing options through theTransitOptions object literal.
Transit requests are time sensitive. Calculations will only be returned for times in the future.
TheTransitOptions object literal contains the following fields:
{arrivalTime:Date,departureTime:Date,modes:[transitMode1,transitMode2]routingPreference:TransitRoutePreference}
These fields are explained below:
arrivalTime(optional) specifies the desired time of arrival as aDateobject. If arrival time is specified, departure time is ignored.departureTime(optional) specifies the desired time of departure as aDateobject. ThedepartureTimewill be ignored ifarrivalTimeis specified. Defaults to now (that is, the current time) if no value is specified for eitherdepartureTimeorarrivalTime.modes(optional) is an array containing one or moreTransitModeobject literals. This field may only be included if the request includes an API key. EachTransitModespecifies a preferred mode of transit. The following values are permitted:BUSindicates that the calculated route should prefer travel by bus.RAILindicates that the calculated route should prefer travel by train, tram, light rail, and subway.SUBWAYindicates that the calculated route should prefer travel by subway.TRAINindicates that the calculated route should prefer travel by train.TRAMindicates that the calculated route should prefer travel by tram and light rail.
routingPreference(optional) specifies preferences for transit routes. Using this option, you can bias the options returned, rather than accepting the default best route chosen by the API. This field may only be specified if the request includes an API key. The following values are permitted:FEWER_TRANSFERSindicates that the calculated route should prefer a limited number of transfers.LESS_WALKINGindicates that the calculated route should prefer limited amounts of walking.
Driving Options
Use thedrivingOptions object to specify a departure time for calculating the best route to your destination given the expected traffic conditions. You can also specify whether you want the estimated time in traffic to be pessimistic, optimistic, or the best estimate based on historical traffic conditions and live traffic.
ThedrivingOptions object contains the following fields:
{departureTime:Date,trafficModel:TrafficModel}
These fields are explained below:
departureTime(required for thedrivingOptionsobject literal to be valid) specifies the desired time of departure as aDateobject. The value must be set to the current time or some time in the future. It cannot be in the past. (The API converts all dates to UTC to ensure consistent handling across time zones.) If you include thedepartureTimein the request, the API returns the best route given the expected traffic conditions at the time, and includes the predicted time in traffic (duration_in_traffic) in the response. If you don't specify a departure time (that is, if the request does not includedrivingOptions), the returned route is a generally good route without taking traffic conditions into account.Caution:If you do not specify a departure time, the route and duration chosen are based on road network and average time-independenttraffic conditions, not current road conditions. Consequently, routes may include roadsthat are temporarily closed. Results for a given request may vary over timedue to changes in the road network, updated average traffic conditions,and the distributed nature of the service. Results may also vary betweennearly-equivalent routes at any time or frequency.trafficModel(optional) specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in theduration_in_trafficfield in the response, which contains the predicted time in traffic based on historical averages. Defaults tobest_guess. The following values are permitted:bestguess(default) indicates that the returnedduration_in_trafficshould be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer thedepartureTimeis to now..pessimisticindicates that the returnedduration_in_trafficshould be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.optimisticindicates that the returnedduration_in_trafficshould be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.
Below is a sampleDistanceMatrixRequest for driving routes, including a departure time and traffic model:
{origins:[{lat:55.93,lng:-3.118},'Greenwich, England'],destinations:['Stockholm, Sweden',{lat:50.087,lng:14.421}],travelMode:'DRIVING',drivingOptions:{departureTime:newDate(Date.now()+N),// for the time N milliseconds from now.trafficModel:'optimistic'}}
Distance Matrix Responses
A successful call to the Distance Matrix service returns aDistanceMatrixResponse object and aDistanceMatrixStatus object. These are passed to the callback function you specified in the request.
TheDistanceMatrixResponse object contains distance and duration information for each origin/destination pair for which a route could be calculated.
{"originAddresses":["Greenwich, Greater London, UK","13 Great Carleton Square, Edinburgh, City of Edinburgh EH16 4, UK"],"destinationAddresses":["Stockholm County, Sweden","Dlouhá 609/2, 110 00 Praha-Staré Město, Česká republika"],"rows":[{"elements":[{"status":"OK","duration":{"value":70778,"text":"19 hours 40 mins"},"distance":{"value":1887508,"text":"1173 mi"}},{"status":"OK","duration":{"value":44476,"text":"12 hours 21 mins"},"distance":{"value":1262780,"text":"785 mi"}}]},{"elements":[{"status":"OK","duration":{"value":96000,"text":"1 day 3 hours"},"distance":{"value":2566737,"text":"1595 mi"}},{"status":"OK","duration":{"value":69698,"text":"19 hours 22 mins"},"distance":{"value":1942009,"text":"1207 mi"}}]}]}
Distance Matrix Results
The supported fields in a response are explained below.
originAddressesis an array containing the locations passed in theoriginsfield of the Distance Matrix request. The addresses are returned as they are formatted by the geocoder.destinationAddressesis an array containing the locations passed in thedestinationsfield, in the format returned by the geocoder.rowsis an array ofDistanceMatrixResponseRowobjects, with each row corresponding to an origin.elementsare children ofrows, and correspond to a pairing of the row's origin with each destination. They contain status, duration, distance, and fare information (if available) for each origin/destination pair.- Each
elementcontains the following fields:status: SeeStatus Codes for a list of possible status codes.duration: The length of time it takes to travel this route, expressed in seconds (thevaluefield) and astext. The textual value is formatted according to theunitSystemspecified in the request (or in metric, if no preference was supplied).duration_in_traffic: The length of time it takes to travel this route taking into account current traffic conditions, expressed in seconds (thevaluefield) and astext. The textual value is formatted according to theunitSystemspecified in the request (or in metric, if no preference was supplied). Theduration_in_trafficis only returned where traffic data is available, themodeis set todriving, anddepartureTimeis included as part of thedistanceMatrixOptionsfield in the request.distance: The total distance of this route, expressed in meters (value) and astext. The textual value is formatted according to theunitSystemspecified in the request (or in metric, if no preference was supplied).fare: Contains the total fare (that is, the total ticket costs) on this route. This property is only returned for transit requests and only for transit providers where fare information is available. The information includes:currency: AnISO 4217 currency code indicating the currency that the amount is expressed in.value: The total fare amount, in the currency specified above.
Status Codes
The Distance Matrix response includes a status code for the response as a whole, as well as a status for each element.
Response Status Codes
Status codes that apply to theDistanceMatrixResponse are passed in theDistanceMatrixStatus object and include:
OK— The request is valid. This status can be returned even if no routes were found between any of the origins and destinations. SeeElement Status Codes for the element-level status information.INVALID_REQUEST— The provided request was invalid. This is often due to missing required fields. See thelist of supported fields above.MAX_ELEMENTS_EXCEEDED— The product of origins and destinations exceeds theper-query limit.MAX_DIMENSIONS_EXCEEDED— Your request contained more than 25 origins, or more than 25 destinations.OVER_QUERY_LIMIT— Your application has requested too many elements within the allowed time period. The request should succeed if you try again after a reasonable amount of time.REQUEST_DENIED— The service denied use of the Distance Matrix service by your web page.UNKNOWN_ERROR— A Distance Matrix request could not be processed due to a server error. The request may succeed if you try again.
Element Status Codes
The following status codes apply to specificDistanceMatrixElement objects:
NOT_FOUND— The origin and/or destination of this pairing could not be geocoded.OK— The response contains a valid result.ZERO_RESULTS— No route could be found between the origin and destination.
Parsing the Results
TheDistanceMatrixResponse object contains onerow for each origin that was passed in the request. Each row contains anelement field for each pairing of that origin with the provided destination(s).
functioncallback(response,status){if(status=='OK'){varorigins=response.originAddresses;vardestinations=response.destinationAddresses;for(vari=0;i<origins.length;i++){varresults=response.rows[i].elements;for(varj=0;j<results.length;j++){varelement=results[j];vardistance=element.distance.text;varduration=element.duration.text;varfrom=origins[i];varto=destinations[j];}}}}
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-11-21 UTC.