A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developers.google.com/maps/documentation/javascript/distancematrix below:

Distance Matrix Service | Maps JavaScript API

Skip to main content Distance Matrix Service

Stay organized with collections Save and categorize content based on your preferences.

Important: Using this service requires enabling the Distance Matrix API (Legacy) on your project. Note: Server-side libraries

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 the Node.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 Matrix

Google'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 the Directions 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:

  1. Go to the Google Cloud console.
  2. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open.
  3. From the list of APIs on the Dashboard, look for Distance Matrix API (Legacy).
  4. If you see the API in the list, you're all set. If the API is not listed, enable it at https://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, see Usage and Billing for the Distance Matrix API (Legacy).

Note: Each query sent to the Distance Matrix service is limited by the number of allowed elements, where the number of origins times the number of destinations defines the number of elements.

Policies

Use of the Distance Matrix service must be in accordance with the policies 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 a callback method to execute upon completion of the request, to process the results.

You access the Distance Matrix service within your code via the google.maps.DistanceMatrixService constructor object. The DistanceMatrixService.getDistanceMatrix() method initiates a request to the Distance Matrix service, passing it a DistanceMatrixRequest object literal containing the origins, destinations, and travel mode, as well as a callback method to execute upon receipt of the response.

var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087692, 14.421150);

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    transitOptions: TransitOptions,
    drivingOptions: DrivingOptions,
    unitSystem: UnitSystem,
    avoidHighways: Boolean,
    avoidTolls: Boolean,
  }, callback);

function callback(response, status) {
  // See Parsing the Results for
  // the basics of a callback function.
}

View example

The DistanceMatrixRequest contains the following fields:

Note: The durationInTraffic field is now deprecated. 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 the drivingOptions field instead. Travel Modes

When calculating times and distances, you can specify which transportation mode to use. The following travel modes are currently supported:

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, the avoidHighways and avoidTolls options are ignored. You can specify transit-specific routing options through the TransitOptions object literal.

Transit requests are time sensitive. Calculations will only be returned for times in the future.

The TransitOptions object literal contains the following fields:

{
  arrivalTime: Date,
  departureTime: Date,
  modes: [transitMode1, transitMode2]
  routingPreference: TransitRoutePreference
}

These fields are explained below:

Driving Options

Use the drivingOptions 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.

The drivingOptions object contains the following fields:

{
  departureTime: Date,
  trafficModel: TrafficModel
}

These fields are explained below:

Below is a sample DistanceMatrixRequest 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: new Date(Date.now() + N),  // for the time N milliseconds from now.
    trafficModel: 'optimistic'
  }
}
Distance Matrix Responses

A successful call to the Distance Matrix service returns a DistanceMatrixResponse object and a DistanceMatrixStatus object. These are passed to the callback function you specified in the request.

The DistanceMatrixResponse 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.

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 the DistanceMatrixResponse are passed in the DistanceMatrixStatus object and include:

Element Status Codes

The following status codes apply to specific DistanceMatrixElement objects:

Parsing the Results

The DistanceMatrixResponse object contains one row for each origin that was passed in the request. Each row contains an element field for each pairing of that origin with the provided destination(s).

function callback(response, status) {
  if (status == 'OK') {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
        var element = results[j];
        var distance = element.distance.text;
        var duration = element.duration.text;
        var from = origins[i];
        var to = destinations[j];
      }
    }
  }
}

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-07-02 UTC.

[[["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-07-02 UTC."],[],[]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4