Запрос и ответ Distance Matrix API (устаревшая версия)

Разработчики из Европейской экономической зоны (ЕЭЗ)

Введение

Запрос к API матрицы расстояний (устаревшая версия) имеет следующий вид:

https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters

где outputFormat может принимать одно из следующих значений:

  • json (рекомендуется) указывает на вывод в формате JSON (JavaScript Object Notation).
  • xml означает вывод в формате XML.

Некоторые параметры являются обязательными, другие — необязательными. Как это принято в URL-адресах, все параметры разделяются символом амперсанда ( & ). Все зарезервированные символы (например, знак плюса "+") должны быть закодированы в формате URL . Список параметров и их возможных значений приведен ниже.

Необходимые параметры

  • пункты назначения

    Одно или несколько мест, которые будут использоваться в качестве конечной точки для расчета расстояния и времени в пути. Параметры параметра «пункты назначения» аналогичны параметрам параметра «пункты отправления».

  • происхождение

    Отправная точка для расчета расстояния и времени в пути. Вы можете указать одно или несколько мест, разделенных символом вертикальной черты (|), в виде идентификатора места, адреса или координат широты/долготы:

    • Идентификатор места : Если вы указываете идентификатор места, перед ним необходимо добавить префикс place_id: .
    • Адрес : Если вы укажете адрес, сервис выполнит геокодирование строки и преобразует её в координаты широты/долготы для вычисления расстояния. Эти координаты могут отличаться от координат, возвращаемых API геокодирования, например, координаты входа в здание, а не его центра.
      Примечание: предпочтительнее использовать идентификаторы мест, а не адреса или координаты широты/долготы. Использование координат всегда приведет к тому, что точка будет привязана к ближайшей к этим координатам дороге, которая может не являться подъездной дорогой к объекту или даже дорогой, которая быстро и безопасно приведет к месту назначения. Использование адреса позволит определить расстояние до центра здания, а не до входа в него.
    • Координаты : Если вы укажете координаты широты/долготы, они будут привязаны к ближайшей дороге. Предпочтительно указывать идентификатор места. Если вы указываете координаты, убедитесь, что между значениями широты и долготы нет пробела.
    • Плюсовые коды должны быть отформатированы как глобальный код или составной код. Форматирование плюсовых кодов показано здесь (плюсы экранируются с помощью url-escaping до %2B, а пробелы — до %20):
      • Глобальный код — это 4-символьный код города, а местный код — 6-символьный или более длинный ( 849VCWC8+R9 кодируется как 849VCWC8%2BR9 ).
      • Составной код — это локальный код из 6 символов или более, содержащий явное указание местоположения (например, CWC8+R9 Mountain View, CA, USA кодируется как CWC8%2BR9%20Mountain%20View%20CA%20USA ).
    • В качестве альтернативы вы можете предоставить закодированный набор координат, используя алгоритм кодирования полилинии . Это особенно полезно, если у вас большое количество исходных точек, поскольку URL-адрес значительно короче при использовании закодированной полилинии.
      • Закодированные полилинии должны начинаться с префикса enc: и завершаться двоеточием : . Например: origins=enc:gfo}EtohhU:
      • Также можно включить несколько закодированных полилиний, разделенных символом вертикальной черты | . Например:
        origins=enc:wc~oAwquwMdlTxiKtqLyiK:|enc:c~vnAamswMvlTor@tjGi}L:|enc:udymA{~bxM:
        

Дополнительные параметры

  • время прибытия

    Указывает предпочтительное время прибытия для маршрутов общественного транспорта в секундах с полуночи 1 января 1970 года по UTC. Можно указать либо departure_time , либо arrival_time , но не оба параметра одновременно. Обратите внимание, что arrival_time должно быть указано целым числом.

  • избегать

    Расстояния могут быть рассчитаны с учетом определенных ограничений. Ограничения указываются с помощью параметра avoid и аргумента этого параметра, указывающего на ограничение, которого следует избегать. Поддерживаются следующие ограничения:

    • tolls указывает на то, что рассчитанный маршрут должен избегать платных дорог/мостов.
    • highways указывает на то, что рассчитанный маршрут должен избегать автомагистралей.
    • ferries означает, что рассчитанный маршрут должен избегать паромов.
    • Указание indoor означает, что рассчитанный маршрут должен избегать ступеней внутри помещений при пеших прогулках и использовании общественного транспорта.

    Можно запросить маршрут, который избегает любой комбинации платных дорог, автомагистралей и паромов, передав оба ограничения параметру avoid. Например, avoid=tolls|highways|ferries .

    Примечание: добавление ограничений не исключает маршруты, включающие в себя ограничение; это смещает результат в сторону более выгодных маршрутов.
  • время отправления

    Указывает предпочтительное время отправления. Вы можете указать время в виде целого числа в секундах с полуночи 1 января 1970 года по UTC. Если указано время departure_time позже 9999-12-31T23:59:59.999999999Z, API установит departure_time 9999-12-31T23:59:59.999999999Z в качестве альтернативы. Вы можете указать значение now, которое устанавливает время отправления на текущее время (с точностью до секунды). Время отправления может быть указано в двух случаях:

    • Для запросов, в которых режим передвижения — транзит: вы можете дополнительно указать одно из значений departure_time или arrival_time . Если ни одно из этих значений не указано, departure_time по умолчанию устанавливается на текущее время (то есть время отправления по умолчанию устанавливается на текущее время).
    • Для запросов, в которых режим поездки — «на автомобиле»: вы можете указать departure_time , чтобы получить маршрут и продолжительность поездки (поле ответа: duration_in_traffic), учитывающие дорожную обстановку. departure_time должно быть установлено на текущее время или на какое-либо время в будущем. Оно не может быть в прошлом.
    Примечание: Если время отправления не указано, выбор маршрута и продолжительности основан на дорожной сети и средних, не зависящих от времени, условиях движения. Результаты для конкретного запроса могут меняться со временем из-за изменений в дорожной сети, обновленных средних условий движения и распределенного характера обслуживания. Результаты также могут различаться между практически идентичными маршрутами в любое время и с любой частотой.
    Примечание: Запросы матрицы расстояний, указывающие departure_time при mode=driving ограничены максимум 100 элементами на запрос. Количество элементов определяется произведением количества пунктов отправления на количество пунктов назначения.
  • язык

    Язык, на котором будут возвращаться результаты.

    • См. список поддерживаемых языков . Google часто обновляет список поддерживаемых языков, поэтому этот список может быть неполным.
    • Если language не указан, API пытается использовать предпочтительный язык, указанный в заголовке Accept-Language .
    • API делает все возможное, чтобы предоставить уличный адрес, понятный как пользователю, так и местным жителям. Для достижения этой цели он возвращает уличные адреса на местном языке, при необходимости транслитерированные в письменность, понятную пользователю, с учетом предпочтительного языка. Все остальные адреса возвращаются на предпочтительном языке. Все компоненты адреса возвращаются на одном языке, который выбирается из первого компонента.
    • Если имя недоступно на предпочитаемом языке, API использует наиболее близкое совпадение.
    • Предпочитаемый язык оказывает небольшое влияние на набор результатов, которые API выбирает для возврата, и на порядок их возврата. Геокодер по-разному интерпретирует сокращения в зависимости от языка, например, сокращения для типов улиц или синонимы, которые могут быть допустимы в одном языке, но не в другом. Например, utca и tér являются синонимами слова «улица» на венгерском языке.
  • режим

    Для расчета расстояний и направлений вы можете указать используемый вид транспорта. По умолчанию используется режим DRIVING . По умолчанию направления рассчитываются как маршруты движения. Поддерживаются следующие виды транспорта:

    • driving (по умолчанию) указывает стандартные маршруты движения или расстояние по дорожной сети.
    • Запросы walking : указания маршрута или расстояния с использованием пешеходных дорожек и тротуаров (где это возможно).
    • Запросы bicycling маршруты или информацию о расстоянии с использованием велосипедных дорожек и предпочтительных улиц (где это возможно).
    • Запросы transit в общественном транспорте указывают маршрут или расстояние (если таковые имеются). Если вы выбрали режим проезда, вы можете дополнительно указать время departure_time или время arrival_time . Если ни одно из этих значений не указано, время departure_time по умолчанию устанавливается на текущее время (то есть время отправления по умолчанию устанавливается на текущее время). Вы также можете дополнительно указать transit_mode и/или transit_routing_preference .
    Примечание: В инструкциях для пешеходов и велосипедистов иногда могут отсутствовать четко обозначенные пешеходные или велосипедные дорожки, поэтому в результатах поиска будут отображаться предупреждения, которые необходимо показать пользователю.
    Примечание: Информация о поездках на общественном транспорте доступна за период до 7 дней в прошлом или до 100 дней в будущем, в зависимости от наличия данных, предоставляемых поставщиками информации. Расписание общественного транспорта часто меняется, доступные поездки могут меняться со временем, и нет гарантии получения стабильных результатов для прогнозов на длительный срок.
  • область

    Код региона указывается в виде двухсимвольного значения ccTLD («домен верхнего уровня») . Большинство кодов ccTLD идентичны кодам ISO 3166-1, за некоторыми заметными исключениями. Например, ccTLD Соединенного Королевства — «uk» (.co.uk), а его код ISO 3166-1 — «gb» (технически обозначающий «Соединенное Королевство Великобритании и Северной Ирландии»).

  • traffic_model

    Указывает предположения, используемые при расчете времени в пробках. Этот параметр влияет на значение, возвращаемое в поле duration_in_traffic в ответе, которое содержит прогнозируемое время в пробках на основе исторических средних значений. Параметр traffic_model может быть указан только для маршрутов движения, где запрос включает departure_time . Доступные значения для этого параметра:

    • best_guess (по умолчанию) указывает, что возвращаемое значение duration_in_traffic должно представлять собой наилучшую оценку времени в пути, учитывая как исторические данные о дорожной ситуации, так и данные о текущей ситуации на дорогах. Данные о текущей ситуации на дорогах становятся более важными, чем ближе departure_time к текущему времени.
    • pessimistic указывает на то, что возвращаемое значение duration_in_traffic в большинстве дней должно быть больше фактического времени в пути, хотя в отдельные дни с особенно плохой дорожной обстановкой это значение может превышаться.
    • optimistic указывает на то, что возвращаемое значение duration_in_traffic должно быть короче фактического времени в пути в большинстве дней, хотя в отдельные дни с особенно благоприятными дорожными условиями оно может быть меньше этого значения.

    Значение по умолчанию параметра best_guess обеспечит наиболее полезные прогнозы для подавляющего большинства сценариев использования. Возможно, прогноз времени в пути, полученный с помощью best_guess будет короче, чем при optimistic , или, наоборот, длиннее, чем при pessimistic , из-за того, как модель прогнозирования best_guess интегрирует информацию о дорожном движении в реальном времени.

  • режим_транзита

    Указывает один или несколько предпочтительных видов транспорта. Этот параметр может быть указан только для направлений движения общественного транспорта. Параметр поддерживает следующие аргументы:

    • bus означает, что рассчитанный маршрут должен отдавать предпочтение поездке на автобусе.
    • subway указывает на то, что рассчитанный маршрут должен отдавать предпочтение передвижению на метро.
    • Указание train означает, что рассчитанный маршрут должен отдавать предпочтение поездке.
    • tram указывает, что рассчитанный маршрут должен отдавать предпочтение передвижению на трамвае и легкорельсовом транспорте.
    • rail указывает, что рассчитанный маршрут должен отдавать предпочтение поездкам на поезде, трамвае, легкорельсовом транспорте и метро. Это эквивалентно transit_mode=train|tram|subway .
  • transit_routing_preference

    Задает предпочтения для маршрутов общественного транспорта. Используя этот параметр, вы можете изменить возвращаемые варианты, вместо того чтобы принимать оптимальный маршрут по умолчанию, выбранный API. Этот параметр может быть указан только для маршрутов общественного транспорта. Параметр поддерживает следующие аргументы:

    • less_walking указывает, что рассчитанный маршрут должен отдавать предпочтение ограниченному количеству пеших прогулок.
    • fewer_transfers указывает, что рассчитанный маршрут должен отдавать предпочтение ограниченному числу пересадок.
  • единицы

    Указывает систему единиц измерения, используемую при отображении результатов.

    Примечание: данная настройка системы единиц измерения влияет только на текст, отображаемый в полях расстояния. Поля расстояния также содержат значения, которые всегда выражаются в метрах.

Примеры запросов

В этом примере для указания координат пункта назначения используются координаты широты и долготы:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626
  &origins=40.6655101%2C-73.89188969999998
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101%2C-73.89188969999998&destinations=40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=YOUR_API_KEY'

В этом примере для указания координат назначения используются коды плюса:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=San%20Francisco
  &origins=849VCWC8%2BR9
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=849VCWC8%2BR9&destinations=San%20Francisco&key=YOUR_API_KEY'

В этом примере показан тот же запрос с использованием закодированной полилинии:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=enc%3A_kjwFjtsbMt%60EgnKcqLcaOzkGari%40naPxhVg%7CJjjb%40cqLcaOzkGari%40naPxhV%3A
  &origins=40.6655101%2C-73.89188969999998
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101%2C-73.89188969999998&destinations=enc%3A_kjwFjtsbMt%60EgnKcqLcaOzkGari%40naPxhVg%7CJjjb%40cqLcaOzkGari%40naPxhV%3A&key=YOUR_API_KEY'

Информация о дорожном движении

Информация о дорожной ситуации используется, когда выполняются все следующие условия (это условия, необходимые для получения поля duration_in_traffic в ответе матрицы расстояний):

  • Параметр mode движения — driving , либо он не указан ( driving — это режим движения по умолчанию).
  • Запрос содержит допустимый параметр departure_time . Параметр departure_time может быть установлен на текущее время или на какое-либо время в будущем. Он не может быть установлен на прошлое.

При желании вы можете добавить в свой запрос параметр traffic_model , чтобы указать предположения, которые будут использоваться при расчете времени пребывания в пробке.

Следующий URL-адрес инициирует запрос матрицы расстояний для расчета расстояний между Бостоном (штат Массачусетс) или Чарлстауном (штат Массачусетс) и Лексингтоном (штат Массачусетс) и Конкордом (штат Массачусетс). Запрос включает время отправления и соответствует всем требованиям для возврата поля duration_in_traffic в ответе матрицы расстояний.

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?departure_time=now
  &destinations=Lexington%2CMA%7CConcord%2CMA
  &origins=Boston%2CMA%7CCharlestown%2CMA
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Boston%2CMA%7CCharlestown%2CMA&destinations=Lexington%2CMA%7CConcord%2CMA&departure_time=now&key=YOUR_API_KEY'

JSON

{
  "destination_addresses": ["Lexington, MA, USA", "Concord, MA, USA"],
  "origin_addresses": ["Boston, MA, USA", "Charlestown, Boston, MA, USA"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "33.3 km", "value": 33253 },
              "duration": { "text": "27 mins", "value": 1620 },
              "duration_in_traffic": { "text": "34 mins", "value": 2019 },
              "status": "OK",
            },
            {
              "distance": { "text": "41.5 km", "value": 41491 },
              "duration": { "text": "33 mins", "value": 1981 },
              "duration_in_traffic": { "text": "39 mins", "value": 2342 },
              "status": "OK",
            },
          ],
      },
      {
        "elements":
          [
            {
              "distance": { "text": "31.1 km", "value": 31100 },
              "duration": { "text": "26 mins", "value": 1543 },
              "duration_in_traffic": { "text": "29 mins", "value": 1754 },
              "status": "OK",
            },
            {
              "distance": { "text": "39.3 km", "value": 39338 },
              "duration": { "text": "32 mins", "value": 1904 },
              "duration_in_traffic": { "text": "35 mins", "value": 2077 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

XML


 OK
 Boston, MA, USA
 Charlestown, Boston, MA, USA
 Lexington, MA, USA
 Concord, MA, USA
 
  
   OK
   
    1620
    27 mins
   
   
    33253
    33.3 km
   
   
    2018
    34 mins
   
  
  
   OK
   
    1981
    33 mins
   
   
    41491
    41.5 km
   
   
    2342
    39 mins
   
  
 
 
  
   OK
   
    1543
    26 mins
   
   
    31100
    31.1 km
   
   
    1759
    29 mins
   
  
  
   OK
   
    1904
    32 mins
   
   
    39338
    39.3 km
   
   
    2077
    35 mins
   
  
 

Модификаторы местоположения

Для указания направления движения водители могут использовать модификаторы местоположения, например, модификатор side_of_road , чтобы указать, по какой стороне дороги двигаться, или указатель направления движения, чтобы задать направление движения.

Укажите, что рассчитанные маршруты должны проходить по определенной стороне дороги.

При указании местоположения вы можете запросить, чтобы рассчитанный маршрут проходил по той стороне дороги, к которой привязана путевая точка, используя префикс side_of_road: :. Например, этот запрос вернет расстояние для длинного маршрута, чтобы транспортное средство оказалось на той стороне дороги, к которой была привязана путевая точка:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=side_of_road%3A37.7663444%2C-122.4412006
  &origins=37.7680296%2C-122.4375126
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=37.7680296%2C-122.4375126&destinations=side_of_road%3A37.7663444%2C-122.4412006&key=YOUR_API_KEY'

При использовании side_of_road: с закодированными полилиниями модификатор применяется к каждой точке вдоль полилинии. Например, оба пункта назначения в этом запросе используют параметр:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=side_of_road%3Aenc%3A%7BoqeF%60fejV%5BnC%3A
  &origins=San%20Francisco%20City%20hall
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=San%20Francisco%20City%20hall&destinations=side_of_road%3Aenc%3A%7BoqeF%60fejV%5BnC%3A&key=YOUR_API_KEY'

Модификатор side_of_road: может использоваться только с этим ограничением:

  • Параметр mode движения — driving , либо он не указан ( driving — это режим движения по умолчанию).

Укажите, что вычисляемые маршруты должны иметь определенное заголовочное обозначение.

При указании местоположения можно запросить, чтобы рассчитанный маршрут проходил через это местоположение с определенным направлением. Это направление задается префиксом heading=X: , где X — целое число градусов от 0 (включительно) до 360 (исключительно). Направление 0 означает север, 90 — восток, и так далее по часовой стрелке. Например, в этом запросе рассчитанный маршрут идет на восток от начальной точки, а затем делает разворот:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=37.773245%2C-122.469502
  &origins=heading%3D90%3A37.773279%2C-122.468780
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=heading%3D90%3A37.773279%2C-122.468780&destinations=37.773245%2C-122.469502&key=YOUR_API_KEY'

Модификатор heading=X: может использоваться только с учетом следующих ограничений:

  • Параметр « mode передвижения» может быть driving , bicycling или не указан ( driving — режим передвижения по умолчанию).
  • Модификатор side_of_road не указан для того же местоположения.
  • Местоположение указывается с помощью значений широты и долготы. Нельзя использовать heading с адресами, идентификаторами мест или закодированными полилиниями.

Запрос и ответы на матрицу расстояний

Ниже приведён пример HTTP-запроса, в котором запрашиваются расстояние и продолжительность поездки из Ванкувера, Британская Колумбия, Канада, и из Сиэтла, Вашингтон, США, в Сан-Франциско, Калифорния, США, и в Викторию, Британская Колумбия, Канада.

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=San%20Francisco%7CVictoria%20BC
  &language=fr-FR
  &mode=bicycling
  &origins=Vancouver%20BC%7CSeattle
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver%20BC%7CSeattle&destinations=San%20Francisco%7CVictoria%20BC&mode=bicycling&language=fr-FR&key=YOUR_API_KEY'

Этот запрос вернет четыре элемента — два источника, умноженные на два пункта назначения:

Ванкувер — Сан-Франциско Ванкувер — Виктория
Из Сиэтла в Сан-Франциско Из Сиэтла в Викторию

Результаты отображаются в виде строк, каждая строка содержит один пункт отправления в паре с каждым пунктом назначения.

JSON

{
  "destination_addresses":
    ["San Francisco, Californie, États-Unis", "Victoria, BC, Canada"],
  "origin_addresses":
    ["Vancouver, BC, Canada", "Seattle, Washington, États-Unis"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "1 712 km", "value": 1711765 },
              "duration": { "text": "3 jours 16 heures", "value": 318119 },
              "status": "OK",
            },
            {
              "distance": { "text": "140 km", "value": 139695 },
              "duration": { "text": "6 heures 49 minutes", "value": 24567 },
              "status": "OK",
            },
          ],
      },
      {
        "elements":
          [
            {
              "distance": { "text": "1 452 km", "value": 1451704 },
              "duration": { "text": "3 jours 2 heures", "value": 266680 },
              "status": "OK",
            },
            {
              "distance": { "text": "146 km", "value": 146500 },
              "duration": { "text": "2 heures 53 minutes", "value": 10374 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

XML


 OK
 Vancouver, BC, Canada
 Seattle, Washington, États-Unis
 San Francisco, Californie, États-Unis
 Victoria, BC, Canada
 
  
   OK
   
    318119
    3 jours 16 heures
   
   
    1711765
    1712 km
   
  
  
   OK
   
    24567
    6 heures 49 minutes
   
   
    139695
    140 km
   
  
 
 
  
   OK
   
    266680
    3 jours 2 heures
   
   
    1451704
    1452 km
   
  
  
   OK
   
    10374
    2 heures 53 minutes
   
   
    146500
    146 km
   
  
 

DistanceMatrixResponse

Поле Необходимый Тип Описание
необходимый Массив<строка>

Массив адресов, возвращенных API из вашего исходного запроса. Как и в случае с origin_addresses , они локализованы, если это необходимо. Этот контент предназначен для чтения в неизмененном виде. Не следует программно обрабатывать отформатированные адреса.

необходимый Массив<строка>

Массив адресов, возвращаемый API из вашего исходного запроса. Эти адреса отформатированы геокодером и локализованы в соответствии с языковым параметром, переданным вместе с запросом. Данный контент предназначен для чтения в неизмененном виде. Не следует программно обрабатывать отформатированные адреса.

необходимый Array< DistanceMatrixRow >

Массив элементов, каждый из которых, в свою очередь, содержит элементы status , duration и distance .

Дополнительную информацию см. в разделе DistanceMatrixRow .

необходимый DistanceMatrixStatus

Содержит информацию о статусе запроса и может включать отладочные данные, которые помогут вам выяснить причину сбоя запроса.

Дополнительную информацию см. в разделе DistanceMatrixStatus .

необязательный нить

Строка, содержащая удобочитаемый текст всех ошибок, возникших в процессе обработки запроса.

DistanceMatrixStatus

Коды состояния, возвращаемые службой.

  • OK означает, что ответ содержит допустимый результат.
  • INVALID_REQUEST указывает на то, что предоставленный запрос недействителен.
  • MAX_ELEMENTS_EXCEEDED указывает на то, что произведение адресов отправления и назначения превышает лимит для каждого запроса.
  • MAX_DIMENSIONS_EXCEEDED указывает на то, что количество источников или получателей превышает лимит на один запрос.
  • OVER_DAILY_LIMIT указывает на любой из следующих параметров:
    • Отсутствует или недействителен ключ API.
    • В вашем аккаунте не включена функция выставления счетов.
    • Установленный самостоятельно лимит использования превышен.
    • Предоставленный способ оплаты больше недействителен (например, срок действия кредитной карты истек).
  • OVER_QUERY_LIMIT указывает на то, что сервис получил слишком много запросов от вашего приложения в течение допустимого периода времени.
  • REQUEST_DENIED указывает на то, что сервис отклонил запрос на использование сервиса Distance Matrix вашим приложением.
  • UNKNOWN_ERROR указывает на то, что запрос матрицы расстояний не удалось обработать из-за ошибки сервера. Возможно, запрос будет выполнен успешно, если вы повторите попытку.

DistanceMatrixRow

Поле Необходимый Тип Описание
необходимый Array< DistanceMatrixElement >

Когда API матрицы расстояний возвращает результаты, он помещает их в массив строк JSON. Даже если результаты не возвращаются (например, когда начальные и/или конечные точки отсутствуют), он все равно возвращает пустой массив.

Строки упорядочены в соответствии со значениями параметра origin запроса. Каждая строка соответствует источнику, а каждый элемент в этой строке соответствует паре значений источника и назначения.

Каждый массив строк содержит один или несколько элементов, которые, в свою очередь, содержат информацию об одной паре «источник-назначение».

Дополнительную информацию см. в разделе DistanceMatrixElement .

Элемент матрицы расстояний

Поле Необходимый Тип Описание
необходимый DistanceMatrixElementStatus

Статус элемента.

Дополнительную информацию см. в разделе DistanceMatrixElementStatus .

необязательный TextValueObject

Общая протяженность этого маршрута, выраженная в метрах (значение) и в текстовом виде. Текстовое значение использует систему единиц, указанную в параметре unit исходного запроса, или регион отправления.

Дополнительную информацию см. в разделе TextValueObject .

необязательный TextValueObject

Время, необходимое для прохождения этого маршрута, выраженное в секундах (поле значения) и в текстовом виде. Текстовое представление локализуется в соответствии с языковым параметром запроса.

Дополнительную информацию см. в разделе TextValueObject .

необязательный TextValueObject

Продолжительность поездки по этому маршруту, рассчитанная на основе текущих и исторических данных о дорожной ситуации. См. параметр запроса traffic_model для получения информации о параметрах, позволяющих выбрать оптимистичный, пессимистичный или приблизительный вариант возвращаемого значения. Продолжительность указывается в секундах (поле value) и в текстовом формате. Текстовое представление локализуется в соответствии с языковым параметром запроса. Продолжительность в данных о дорожной ситуации возвращается только в том случае, если выполняются все следующие условия:

  • Запрос включает параметр departure_time .
  • Информация о дорожной ситуации на запрошенном маршруте доступна.
  • Параметр режима установлен в положение "вождение".

Дополнительную информацию см. в разделе TextValueObject .

необязательный Стоимость проезда

Если указана, содержит общую стоимость проезда (то есть общую стоимость билета) по данному маршруту. Эта информация возвращается только для запросов на проезд и только для транспортных компаний, у которых доступна информация о тарифах.

Более подробная информация в разделе «Тарифы» .

Стоимость проезда

Общая стоимость проезда по маршруту.

{
  "currency" : "USD",
  "value" : 6,
  "text" : "$6.00"
}
Поле Необходимый Тип Описание
необходимый нить

Код валюты ISO 4217, указывающий валюту, в которой выражена сумма.

необходимый нить

Общая сумма оплаты, отформатированная на запрошенном языке.

необходимый число

Общая сумма проезда в указанной валюте.

DistanceMatrixElementStatus

  • OK означает, что ответ содержит допустимый результат.
  • NOT_FOUND указывает на то, что местоположение пункта отправления и/или назначения данной пары не удалось определить географически.
  • ZERO_RESULTS означает, что маршрут между пунктом отправления и пунктом назначения не найден.
  • MAX_ROUTE_LENGTH_EXCEEDED указывает на то, что запрошенный маршрут слишком длинный и не может быть обработан.

TextValueObject

Объект, содержащий числовое значение и его отформатированное текстовое представление.

Поле Необходимый Тип Описание
необходимый нить

Строковое значение.

необходимый число

Числовое значение.

,
Разработчики из Европейской экономической зоны (ЕЭЗ)

Введение

Запрос к API матрицы расстояний (устаревшая версия) имеет следующий вид:

https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters

где outputFormat может принимать одно из следующих значений:

  • json (рекомендуется) указывает на вывод в формате JSON (JavaScript Object Notation).
  • xml означает вывод в формате XML.

Некоторые параметры являются обязательными, другие — необязательными. Как это принято в URL-адресах, все параметры разделяются символом амперсанда ( & ). Все зарезервированные символы (например, знак плюса "+") должны быть закодированы в формате URL . Список параметров и их возможных значений приведен ниже.

Необходимые параметры

  • пункты назначения

    Одно или несколько мест, которые будут использоваться в качестве конечной точки для расчета расстояния и времени в пути. Параметры параметра «пункты назначения» аналогичны параметрам параметра «пункты отправления».

  • происхождение

    Отправная точка для расчета расстояния и времени в пути. Вы можете указать одно или несколько мест, разделенных символом вертикальной черты (|), в виде идентификатора места, адреса или координат широты/долготы:

    • Идентификатор места : Если вы указываете идентификатор места, перед ним необходимо добавить префикс place_id: .
    • Адрес : Если вы укажете адрес, сервис выполнит геокодирование строки и преобразует её в координаты широты/долготы для вычисления расстояния. Эти координаты могут отличаться от координат, возвращаемых API геокодирования, например, координаты входа в здание, а не его центра.
      Примечание: предпочтительнее использовать идентификаторы мест, а не адреса или координаты широты/долготы. Использование координат всегда приведет к тому, что точка будет привязана к ближайшей к этим координатам дороге, которая может не являться подъездной дорогой к объекту или даже дорогой, которая быстро и безопасно приведет к месту назначения. Использование адреса позволит определить расстояние до центра здания, а не до входа в него.
    • Координаты : Если вы укажете координаты широты/долготы, они будут привязаны к ближайшей дороге. Предпочтительно указывать идентификатор места. Если вы указываете координаты, убедитесь, что между значениями широты и долготы нет пробела.
    • Плюсовые коды должны быть отформатированы как глобальный код или составной код. Форматирование плюсовых кодов показано здесь (плюсы экранируются с помощью url-escaping до %2B, а пробелы — до %20):
      • Глобальный код — это 4-символьный код города, а местный код — 6-символьный или более длинный ( 849VCWC8+R9 кодируется как 849VCWC8%2BR9 ).
      • Составной код — это локальный код из 6 символов или более, содержащий явное указание местоположения (например, CWC8+R9 Mountain View, CA, USA кодируется как CWC8%2BR9%20Mountain%20View%20CA%20USA ).
    • В качестве альтернативы вы можете предоставить закодированный набор координат, используя алгоритм кодирования полилинии . Это особенно полезно, если у вас большое количество исходных точек, поскольку URL-адрес значительно короче при использовании закодированной полилинии.
      • Закодированные полилинии должны начинаться с префикса enc: и завершаться двоеточием : . Например: origins=enc:gfo}EtohhU:
      • Также можно включить несколько закодированных полилиний, разделенных символом вертикальной черты | . Например:
        origins=enc:wc~oAwquwMdlTxiKtqLyiK:|enc:c~vnAamswMvlTor@tjGi}L:|enc:udymA{~bxM:
        

Дополнительные параметры

  • время прибытия

    Указывает предпочтительное время прибытия для маршрутов общественного транспорта в секундах с полуночи 1 января 1970 года по UTC. Можно указать либо departure_time , либо arrival_time , но не оба параметра одновременно. Обратите внимание, что arrival_time должно быть указано целым числом.

  • избегать

    Расстояния могут быть рассчитаны с учетом определенных ограничений. Ограничения указываются с помощью параметра avoid и аргумента этого параметра, указывающего на ограничение, которого следует избегать. Поддерживаются следующие ограничения:

    • tolls указывает на то, что рассчитанный маршрут должен избегать платных дорог/мостов.
    • highways указывает на то, что рассчитанный маршрут должен избегать автомагистралей.
    • ferries означает, что рассчитанный маршрут должен избегать паромов.
    • Указание indoor означает, что рассчитанный маршрут должен избегать ступеней внутри помещений при пеших прогулках и использовании общественного транспорта.

    Можно запросить маршрут, который избегает любой комбинации платных дорог, автомагистралей и паромов, передав оба ограничения параметру avoid. Например, avoid=tolls|highways|ferries .

    Примечание: добавление ограничений не исключает маршруты, включающие в себя ограничение; это смещает результат в сторону более выгодных маршрутов.
  • время отправления

    Указывает предпочтительное время отправления. Вы можете указать время в виде целого числа в секундах с полуночи 1 января 1970 года по UTC. Если указано время departure_time позже 9999-12-31T23:59:59.999999999Z, API установит departure_time 9999-12-31T23:59:59.999999999Z в качестве альтернативы. Вы можете указать значение now, которое устанавливает время отправления на текущее время (с точностью до секунды). Время отправления может быть указано в двух случаях:

    • Для запросов, в которых режим передвижения — транзит: вы можете дополнительно указать одно из значений departure_time или arrival_time . Если ни одно из этих значений не указано, departure_time по умолчанию устанавливается на текущее время (то есть время отправления по умолчанию устанавливается на текущее время).
    • Для запросов, в которых режим поездки — «на автомобиле»: вы можете указать departure_time , чтобы получить маршрут и продолжительность поездки (поле ответа: duration_in_traffic), учитывающие дорожную обстановку. departure_time должно быть установлено на текущее время или на какое-либо время в будущем. Оно не может быть в прошлом.
    Примечание: Если время отправления не указано, выбор маршрута и продолжительности основан на дорожной сети и средних, не зависящих от времени, условиях движения. Результаты для конкретного запроса могут меняться со временем из-за изменений в дорожной сети, обновленных средних условий движения и распределенного характера обслуживания. Результаты также могут различаться между практически идентичными маршрутами в любое время и с любой частотой.
    Примечание: Запросы матрицы расстояний, указывающие departure_time при mode=driving ограничены максимум 100 элементами на запрос. Количество элементов определяется произведением количества пунктов отправления на количество пунктов назначения.
  • язык

    Язык, на котором будут возвращаться результаты.

    • См. список поддерживаемых языков . Google часто обновляет список поддерживаемых языков, поэтому этот список может быть неполным.
    • Если language не указан, API пытается использовать предпочтительный язык, указанный в заголовке Accept-Language .
    • API делает все возможное, чтобы предоставить уличный адрес, понятный как пользователю, так и местным жителям. Для достижения этой цели он возвращает уличные адреса на местном языке, при необходимости транслитерированные в письменность, понятную пользователю, с учетом предпочтительного языка. Все остальные адреса возвращаются на предпочтительном языке. Все компоненты адреса возвращаются на одном языке, который выбирается из первого компонента.
    • Если имя недоступно на предпочитаемом языке, API использует наиболее близкое совпадение.
    • Предпочитаемый язык оказывает небольшое влияние на набор результатов, которые API выбирает для возврата, и на порядок их возврата. Геокодер по-разному интерпретирует сокращения в зависимости от языка, например, сокращения для типов улиц или синонимы, которые могут быть допустимы в одном языке, но не в другом. Например, utca и tér являются синонимами слова «улица» на венгерском языке.
  • режим

    Для расчета расстояний и направлений вы можете указать используемый вид транспорта. По умолчанию используется режим DRIVING . По умолчанию направления рассчитываются как маршруты движения. Поддерживаются следующие виды транспорта:

    • driving (по умолчанию) указывает стандартные маршруты движения или расстояние по дорожной сети.
    • Запросы walking : указания маршрута или расстояния с использованием пешеходных дорожек и тротуаров (где это возможно).
    • Запросы bicycling маршруты или информацию о расстоянии с использованием велосипедных дорожек и предпочтительных улиц (где это возможно).
    • Запросы transit в общественном транспорте указывают маршрут или расстояние (если таковые имеются). Если вы выбрали режим проезда, вы можете дополнительно указать время departure_time или время arrival_time . Если ни одно из этих значений не указано, время departure_time по умолчанию устанавливается на текущее время (то есть время отправления по умолчанию устанавливается на текущее время). Вы также можете дополнительно указать transit_mode и/или transit_routing_preference .
    Примечание: В инструкциях для пешеходов и велосипедистов иногда могут отсутствовать четко обозначенные пешеходные или велосипедные дорожки, поэтому в результатах поиска будут отображаться предупреждения, которые необходимо показать пользователю.
    Примечание: Информация о поездках на общественном транспорте доступна за период до 7 дней в прошлом или до 100 дней в будущем, в зависимости от наличия данных, предоставляемых поставщиками информации. Расписание общественного транспорта часто меняется, доступные поездки могут меняться со временем, и нет гарантии получения стабильных результатов для прогнозов на длительный срок.
  • область

    Код региона указывается в виде двухсимвольного значения ccTLD («домен верхнего уровня») . Большинство кодов ccTLD идентичны кодам ISO 3166-1, за некоторыми заметными исключениями. Например, ccTLD Соединенного Королевства — «uk» (.co.uk), а его код ISO 3166-1 — «gb» (технически обозначающий «Соединенное Королевство Великобритании и Северной Ирландии»).

  • traffic_model

    Указывает предположения, используемые при расчете времени в пробках. Этот параметр влияет на значение, возвращаемое в поле duration_in_traffic в ответе, которое содержит прогнозируемое время в пробках на основе исторических средних значений. Параметр traffic_model может быть указан только для маршрутов движения, где запрос включает departure_time . Доступные значения для этого параметра:

    • best_guess (по умолчанию) указывает, что возвращаемое значение duration_in_traffic должно представлять собой наилучшую оценку времени в пути, учитывая как исторические данные о дорожной ситуации, так и данные о текущей ситуации на дорогах. Данные о текущей ситуации на дорогах становятся более важными, чем ближе departure_time к текущему времени.
    • pessimistic указывает на то, что возвращаемое значение duration_in_traffic в большинстве дней должно быть больше фактического времени в пути, хотя в отдельные дни с особенно плохой дорожной обстановкой это значение может превышаться.
    • optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.

    The default value of best_guess will give the most useful predictions for the vast majority of use cases. It is possible the best_guess travel time prediction may be shorter than optimistic , or alternatively, longer than pessimistic , due to the way the best_guess prediction model integrates live traffic information.

  • transit_mode

    Specifies one or more preferred modes of transit. This parameter may only be specified for transit directions. The parameter supports the following arguments:

    • bus indicates that the calculated route should prefer travel by bus.
    • subway indicates that the calculated route should prefer travel by subway.
    • train indicates that the calculated route should prefer travel by train.
    • tram indicates that the calculated route should prefer travel by tram and light rail.
    • rail indicates that the calculated route should prefer travel by train, tram, light rail, and subway. This is equivalent to transit_mode=train|tram|subway .
  • transit_routing_preference

    Specifies preferences for transit routes. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. This parameter may only be specified for transit directions. The parameter supports the following arguments:

    • less_walking indicates that the calculated route should prefer limited amounts of walking.
    • fewer_transfers indicates that the calculated route should prefer a limited number of transfers.
  • единицы

    Specifies the unit system to use when displaying results.

    Note: this unit system setting only affects the text displayed within distance fields. The distance fields also contain values which are always expressed in meters.

Примеры запросов

This example uses latitude/longitude coordinates to specify the destination coordinates:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626
  &origins=40.6655101%2C-73.89188969999998
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101%2C-73.89188969999998&destinations=40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=YOUR_API_KEY'

This example uses plus codes to specify the destination coordinates:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=San%20Francisco
  &origins=849VCWC8%2BR9
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=849VCWC8%2BR9&destinations=San%20Francisco&key=YOUR_API_KEY'

This example shows the same request using an encoded polyline:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=enc%3A_kjwFjtsbMt%60EgnKcqLcaOzkGari%40naPxhVg%7CJjjb%40cqLcaOzkGari%40naPxhV%3A
  &origins=40.6655101%2C-73.89188969999998
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101%2C-73.89188969999998&destinations=enc%3A_kjwFjtsbMt%60EgnKcqLcaOzkGari%40naPxhVg%7CJjjb%40cqLcaOzkGari%40naPxhV%3A&key=YOUR_API_KEY'

Traffic information

Traffic information is used when all the following apply (these are the conditions required to receive the duration_in_traffic field in the Distance Matrix response):

  • The travel mode parameter is driving , or is not specified ( driving is the default travel mode).
  • The request includes a valid departure_time parameter . The departure_time can be set to the current time or some time in the future. It cannot be in the past.

Optionally, you can include the traffic_model parameter in your request to specify the assumptions to use when calculating time in traffic.

The following URL initiates a Distance Matrix request for driving distances between Boston, MA or Charlestown, MA, and Lexington, MA and Concord, MA. The request includes a departure time, meeting all the requirements to return the duration_in_traffic field in the Distance Matrix response.

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?departure_time=now
  &destinations=Lexington%2CMA%7CConcord%2CMA
  &origins=Boston%2CMA%7CCharlestown%2CMA
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Boston%2CMA%7CCharlestown%2CMA&destinations=Lexington%2CMA%7CConcord%2CMA&departure_time=now&key=YOUR_API_KEY'

JSON

{
  "destination_addresses": ["Lexington, MA, USA", "Concord, MA, USA"],
  "origin_addresses": ["Boston, MA, USA", "Charlestown, Boston, MA, USA"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "33.3 km", "value": 33253 },
              "duration": { "text": "27 mins", "value": 1620 },
              "duration_in_traffic": { "text": "34 mins", "value": 2019 },
              "status": "OK",
            },
            {
              "distance": { "text": "41.5 km", "value": 41491 },
              "duration": { "text": "33 mins", "value": 1981 },
              "duration_in_traffic": { "text": "39 mins", "value": 2342 },
              "status": "OK",
            },
          ],
      },
      {
        "elements":
          [
            {
              "distance": { "text": "31.1 km", "value": 31100 },
              "duration": { "text": "26 mins", "value": 1543 },
              "duration_in_traffic": { "text": "29 mins", "value": 1754 },
              "status": "OK",
            },
            {
              "distance": { "text": "39.3 km", "value": 39338 },
              "duration": { "text": "32 mins", "value": 1904 },
              "duration_in_traffic": { "text": "35 mins", "value": 2077 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

XML


 OK
 Boston, MA, USA
 Charlestown, Boston, MA, USA
 Lexington, MA, USA
 Concord, MA, USA
 
  
   OK
   
    1620
    27 mins
   
   
    33253
    33.3 km
   
   
    2018
    34 mins
   
  
  
   OK
   
    1981
    33 mins
   
   
    41491
    41.5 km
   
   
    2342
    39 mins
   
  
 
 
  
   OK
   
    1543
    26 mins
   
   
    31100
    31.1 km
   
   
    1759
    29 mins
   
  
  
   OK
   
    1904
    32 mins
   
   
    39338
    39.3 km
   
   
    2077
    35 mins
   
  
 

Location Modifiers

You can use location modifiers to indicate how drivers should approach a particular location, by using the side_of_road modifier to specify which side of the road to use, or by specifying a heading to indicate the correct direction of travel.

Specify that calculated routes must pass through a particular side of the road

When specifying a location, you can request that the calculated route go through whichever side of the road the waypoint is biased towards by using the side_of_road: prefix. For example, this request will return the distance for a long route so that the vehicle ends on the side of the road to which the waypoint was biased:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=side_of_road%3A37.7663444%2C-122.4412006
  &origins=37.7680296%2C-122.4375126
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=37.7680296%2C-122.4375126&destinations=side_of_road%3A37.7663444%2C-122.4412006&key=YOUR_API_KEY'

When using side_of_road: with encoded polylines, the modifier is applied to every location along the polyline. For example, the two destinations in this request both use the parameter:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=side_of_road%3Aenc%3A%7BoqeF%60fejV%5BnC%3A
  &origins=San%20Francisco%20City%20hall
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=San%20Francisco%20City%20hall&destinations=side_of_road%3Aenc%3A%7BoqeF%60fejV%5BnC%3A&key=YOUR_API_KEY'

The side_of_road: modifier may only be used with this restriction:

  • The travel mode parameter is driving , or is not specified ( driving is the default travel mode).

Specify that calculated routes should have a particular heading

When specifying a location, you can request that the calculated route go through the location in a particular heading. This heading is specified with the prefix heading=X: , where X is an integer degree value between 0 (inclusive) and 360 (exclusive). A heading of 0 indicates North, 90 indicates East, continuing clockwise. For example, in this request the calculated route goes east from the origin, then takes a U-turn:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=37.773245%2C-122.469502
  &origins=heading%3D90%3A37.773279%2C-122.468780
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=heading%3D90%3A37.773279%2C-122.468780&destinations=37.773245%2C-122.469502&key=YOUR_API_KEY'

The heading=X: modifier may only be used with these restrictions:

  • The travel mode parameter is driving , bicycling , or is not specified ( driving is the default travel mode).
  • The side_of_road modifier is not specified for the same location.
  • The location is specified with a latitude/longitude value. You may not use heading with addresses, Place IDs, or encoded polylines.

Distance Matrix request and responses

A sample HTTP request is shown below, requesting distance and duration from Vancouver, BC, Canada and from Seattle, WA, USA, to San Francisco, CA, USA and to Victoria, BC, Canada.

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=San%20Francisco%7CVictoria%20BC
  &language=fr-FR
  &mode=bicycling
  &origins=Vancouver%20BC%7CSeattle
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver%20BC%7CSeattle&destinations=San%20Francisco%7CVictoria%20BC&mode=bicycling&language=fr-FR&key=YOUR_API_KEY'

This request will return four elements - two origins times two destinations:

Vancouver to San Francisco Ванкувер — Виктория
Seattle to San Francisco Seattle to Victoria

Results are returned in rows, each row containing one origin paired with each destination.

JSON

{
  "destination_addresses":
    ["San Francisco, Californie, États-Unis", "Victoria, BC, Canada"],
  "origin_addresses":
    ["Vancouver, BC, Canada", "Seattle, Washington, États-Unis"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "1 712 km", "value": 1711765 },
              "duration": { "text": "3 jours 16 heures", "value": 318119 },
              "status": "OK",
            },
            {
              "distance": { "text": "140 km", "value": 139695 },
              "duration": { "text": "6 heures 49 minutes", "value": 24567 },
              "status": "OK",
            },
          ],
      },
      {
        "elements":
          [
            {
              "distance": { "text": "1 452 km", "value": 1451704 },
              "duration": { "text": "3 jours 2 heures", "value": 266680 },
              "status": "OK",
            },
            {
              "distance": { "text": "146 km", "value": 146500 },
              "duration": { "text": "2 heures 53 minutes", "value": 10374 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

XML


 OK
 Vancouver, BC, Canada
 Seattle, Washington, États-Unis
 San Francisco, Californie, États-Unis
 Victoria, BC, Canada
 
  
   OK
   
    318119
    3 jours 16 heures
   
   
    1711765
    1712 km
   
  
  
   OK
   
    24567
    6 heures 49 minutes
   
   
    139695
    140 km
   
  
 
 
  
   OK
   
    266680
    3 jours 2 heures
   
   
    1451704
    1452 km
   
  
  
   OK
   
    10374
    2 heures 53 minutes
   
   
    146500
    146 km
   
  
 

DistanceMatrixResponse

Поле Необходимый Тип Описание
необходимый Array<string>

An array of addresses as returned by the API from your original request. As with origin_addresses , these are localized if appropriate. This content is meant to be read as-is. Don't programmatically parse the formatted addresses.

необходимый Array<string>

An array of addresses as returned by the API from your original request. These are formatted by the geocoder and localized according to the language parameter passed with the request. This content is meant to be read as-is. Don't programmatically parse the formatted addresses.

необходимый Array< DistanceMatrixRow >

An array of elements, which in turn each contain a status , duration , and distance element.

See DistanceMatrixRow for more information.

необходимый DistanceMatrixStatus

Contains the status of the request, and may contain debugging information to help you track down why the request failed.

See DistanceMatrixStatus for more information.

необязательный нить

A string containing the human-readable text of any errors encountered while the request was being processed.

DistanceMatrixStatus

Status codes returned by service.

  • OK indicates the response contains a valid result.
  • INVALID_REQUEST indicates that the provided request was invalid.
  • MAX_ELEMENTS_EXCEEDED indicates that the product of origins and destinations exceeds the per-query limit.
  • MAX_DIMENSIONS_EXCEEDED indicates that the number of origins or destinations exceeds the per-query limit.
  • OVER_DAILY_LIMIT indicates any of the following:
    • The API key is missing or invalid.
    • Billing has not been enabled on your account.
    • A self-imposed usage cap has been exceeded.
    • The provided method of payment is no longer valid (for example, a credit card has expired).
  • OVER_QUERY_LIMIT indicates the service has received too many requests from your application within the allowed time period.
  • REQUEST_DENIED indicates that the service denied use of the Distance Matrix service by your application.
  • UNKNOWN_ERROR indicates a Distance Matrix request couldn't be processed due to a server error. The request may succeed if you try again.

DistanceMatrixRow

Поле Необходимый Тип Описание
необходимый Array< DistanceMatrixElement >

When the Distance Matrix API returns results, it places them within a JSON rows array. Even if no results are returned (such as when the origins and/or destinations don't exist), it still returns an empty array.

Rows are ordered according to the values in the origin parameter of the request. Each row corresponds to an origin, and each element within that row corresponds to a pairing of the origin with a destination value.

Each row array contains one or more element entries, which in turn contain the information about a single origin-destination pairing.

See DistanceMatrixElement for more information.

DistanceMatrixElement

Поле Необходимый Тип Описание
необходимый DistanceMatrixElementStatus

A status for the element.

See DistanceMatrixElementStatus for more information.

необязательный TextValueObject

The total distance of this route, expressed in meters (value) and as text. The textual value uses the unit system specified with the unit parameter of the original request, or the origin's region.

See TextValueObject for more information.

необязательный TextValueObject

The length of time it takes to travel this route, expressed in seconds (the value field) and as text. The textual representation is localized according to the query's language parameter.

See TextValueObject for more information.

необязательный TextValueObject

The length of time it takes to travel this route, based on current and historical traffic conditions. See the traffic_model request parameter for the options you can use to request that the returned value is optimistic, pessimistic, or a best-guess estimate. The duration is expressed in seconds (the value field) and as text. The textual representation is localized according to the query's language parameter. The duration in traffic is returned only if all of the following are true:

  • The request includes a departure_time parameter.
  • Traffic conditions are available for the requested route.
  • The mode parameter is set to driving.

See TextValueObject for more information.

необязательный Стоимость проезда

If present, 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.

See Fare for more information.

Стоимость проезда

The total fare for the route.

{
  "currency" : "USD",
  "value" : 6,
  "text" : "$6.00"
}
Поле Необходимый Тип Описание
необходимый нить

An ISO 4217 currency code indicating the currency that the amount is expressed in.

необходимый нить

The total fare amount, formatted in the requested language.

необходимый число

The total fare amount, in the currency specified.

DistanceMatrixElementStatus

  • OK indicates the response contains a valid result.
  • NOT_FOUND indicates that the origin and/or destination of this pairing couldn't be geocoded.
  • ZERO_RESULTS indicates no route could be found between the origin and destination.
  • MAX_ROUTE_LENGTH_EXCEEDED indicates the requested route is too long and cannot be processed.

TextValueObject

An object containing a numeric value and its formatted text representation.

Поле Необходимый Тип Описание
необходимый нить

String value.

необходимый число

Numeric value.

,
European Economic Area (EEA) developers

Введение

A Distance Matrix API (Legacy) request takes the following form:

https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters

where outputFormat may be either of the following values:

  • json (recommended) indicates output in JavaScript Object Notation (JSON).
  • xml indicates output as XML.

Certain parameters are required while others are optional. As is standard in URLs, all parameters are separated using the ampersand ( & ) character. All reserved characters (for example the plus sign "+") must be URL-encoded . The list of parameters and their possible values are enumerated below.

Required parameters

  • пункты назначения

    One or more locations to use as the finishing point for calculating travel distance and time. The options for the destinations parameter are the same as for the origins parameter.

  • происхождение

    The starting point for calculating travel distance and time. You can supply one or more locations separated by the pipe character (|), in the form of a place ID, an address, or latitude/longitude coordinates:

    • Place ID : If you supply a place ID, you must prefix it with place_id: .
    • Address : If you pass an address, the service geocodes the string and converts it to a latitude/longitude coordinate to calculate distance. This coordinate may be different from that returned by the Geocoding API, for example a building entrance rather than its center.
      Note: using place IDs is preferred over using addresses or latitude/longitude coordinates. Using coordinates will always result in the point being snapped to the road nearest to those coordinates - which may not be an access point to the property, or even a road that will quickly or safely lead to the destination. Using the address will provide the distance to the center of the building, as opposed to an entrance to the building.
    • Coordinates : If you pass latitude/longitude coordinates, they they will snap to the nearest road. Passing a place ID is preferred. If you do pass coordinates, ensure that no space exists between the latitude and longitude values.
    • Plus codes must be formatted as a global code or a compound code. Format plus codes as shown here (plus signs are url-escaped to %2B and spaces are url-escaped to %20):
      • global code is a 4 character area code and 6 character or longer local code ( 849VCWC8+R9 is encoded to 849VCWC8%2BR9 ).
      • compound code is a 6 character or longer local code with an explicit location ( CWC8+R9 Mountain View, CA, USA is encoded to CWC8%2BR9%20Mountain%20View%20CA%20USA ).
    • Encoded Polyline Alternatively, you can supply an encoded set of coordinates using the Encoded Polyline Algorithm . This is particularly useful if you have a large number of origin points, because the URL is significantly shorter when using an encoded polyline.
      • Encoded polylines must be prefixed with enc: and followed by a colon : . For example: origins=enc:gfo}EtohhU:
      • You can also include multiple encoded polylines, separated by the pipe character | . For example:
        origins=enc:wc~oAwquwMdlTxiKtqLyiK:|enc:c~vnAamswMvlTor@tjGi}L:|enc:udymA{~bxM:
        

Дополнительные параметры

  • arrival_time

    Specifies the preferred time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. You can specify either departure_time or arrival_time , but not both. Note that arrival_time must be specified as an integer.

  • избегать

    Distances may be calculated that adhere to certain restrictions. Restrictions are indicated by use of the avoid parameter, and an argument to that parameter indicating the restriction to avoid. The following restrictions are supported:

    • tolls indicates that the calculated route should avoid toll roads/bridges.
    • highways indicates that the calculated route should avoid highways.
    • ferries indicates that the calculated route should avoid ferries.
    • indoor indicates that the calculated route should avoid indoor steps for walking and transit directions.

    It's possible to request a route that avoids any combination of tolls, highways and ferries by passing both restrictions to the avoid parameter. For example avoid=tolls|highways|ferries .

    Note: The addition of restrictions does not preclude routes that include the restricted feature; it biases the result to more favorable routes.
  • departure_time

    Specifies the preferred time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. If a departure_time later than 9999-12-31T23:59:59.999999999Z is specified, the API will fall back the departure_time to 9999-12-31T23:59:59.999999999Z. Alternatively, you can specify a value of now, which sets the departure time to the current time (correct to the nearest second). The departure time may be specified in two cases:

    • For requests where the travel mode is transit: You can optionally specify one of departure_time or arrival_time . If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time).
    • For requests where the travel mode is driving: You can specify the departure_time to receive a route and trip duration (response field: duration_in_traffic) that take traffic conditions into account. The departure_time must be set to the current time or some time in the future. It cannot be in the past.
    Note: If departure time is not specified, choice of route and duration are based on road network and average time-independent traffic conditions. Results for a given request may vary over time due to changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency.
    Note: Distance Matrix requests specifying departure_time when mode=driving are limited to a maximum of 100 elements per request. The number of origins times the number of destinations defines the number of elements.
  • язык

    The language in which to return results.

    • See the list of supported languages . Google often updates the supported languages, so this list may not be exhaustive.
    • If language is not supplied, the API attempts to use the preferred language as specified in the Accept-Language header.
    • The API does its best to provide a street address that is readable for both the user and locals. To achieve that goal, it returns street addresses in the local language, transliterated to a script readable by the user if necessary, observing the preferred language. All other addresses are returned in the preferred language. Address components are all returned in the same language, which is chosen from the first component.
    • If a name is not available in the preferred language, the API uses the closest match.
    • The preferred language has a small influence on the set of results that the API chooses to return, and the order in which they are returned. The geocoder interprets abbreviations differently depending on language, such as the abbreviations for street types, or synonyms that may be valid in one language but not in another. For example, utca and tér are synonyms for street in Hungarian.
  • режим

    For the calculation of distances and directions, you may specify the transportation mode to use. By default, DRIVING mode is used. By default, directions are calculated as driving directions. The following travel modes are supported:

    • driving (default) indicates standard driving directions or distance using the road network.
    • walking requests walking directions or distance using pedestrian paths & sidewalks (where available).
    • bicycling requests bicycling directions or distance using bicycle paths & preferred streets (where available).
    • transit requests directions or distance using public transit routes (where available). If you set the mode to transit, you can optionally specify either a departure_time or an arrival_time . If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time). You can also optionally include a transit_mode and/or a transit_routing_preference .
    Note: Both walking and bicycling directions may sometimes not include clear pedestrian or bicycling paths, so these directions will return warnings in the returned result which you must display to the user.
    Note: Transit trips are available for up to 7 days in the past or up to 100 days in the future, subject to availability of transit information supplied by data providers. Transit schedules change frequently, available transit trips may change over time and there is no guarantee to provide consistent results for predictions far in advance.
  • область

    The region code, specified as a ccTLD ("top-level domain") two-character value. Most ccTLD codes are identical to ISO 3166-1 codes, with some notable exceptions. For example, the United Kingdom's ccTLD is "uk" (.co.uk) while its ISO 3166-1 code is "gb" (technically for the entity of "The United Kingdom of Great Britain and Northern Ireland").

  • traffic_model

    Specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. The traffic_model parameter may only be specified for driving directions where the request includes a departure_time . The available values for this parameter are:

    • best_guess (default) indicates that the returned duration_in_traffic should 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 the departure_time is to now.
    • pessimistic indicates that the returned duration_in_traffic should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.
    • optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.

    The default value of best_guess will give the most useful predictions for the vast majority of use cases. It is possible the best_guess travel time prediction may be shorter than optimistic , or alternatively, longer than pessimistic , due to the way the best_guess prediction model integrates live traffic information.

  • transit_mode

    Specifies one or more preferred modes of transit. This parameter may only be specified for transit directions. The parameter supports the following arguments:

    • bus indicates that the calculated route should prefer travel by bus.
    • subway indicates that the calculated route should prefer travel by subway.
    • train indicates that the calculated route should prefer travel by train.
    • tram indicates that the calculated route should prefer travel by tram and light rail.
    • rail indicates that the calculated route should prefer travel by train, tram, light rail, and subway. This is equivalent to transit_mode=train|tram|subway .
  • transit_routing_preference

    Specifies preferences for transit routes. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. This parameter may only be specified for transit directions. The parameter supports the following arguments:

    • less_walking indicates that the calculated route should prefer limited amounts of walking.
    • fewer_transfers indicates that the calculated route should prefer a limited number of transfers.
  • единицы

    Specifies the unit system to use when displaying results.

    Note: this unit system setting only affects the text displayed within distance fields. The distance fields also contain values which are always expressed in meters.

Примеры запросов

This example uses latitude/longitude coordinates to specify the destination coordinates:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626
  &origins=40.6655101%2C-73.89188969999998
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101%2C-73.89188969999998&destinations=40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=YOUR_API_KEY'

This example uses plus codes to specify the destination coordinates:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=San%20Francisco
  &origins=849VCWC8%2BR9
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=849VCWC8%2BR9&destinations=San%20Francisco&key=YOUR_API_KEY'

This example shows the same request using an encoded polyline:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=enc%3A_kjwFjtsbMt%60EgnKcqLcaOzkGari%40naPxhVg%7CJjjb%40cqLcaOzkGari%40naPxhV%3A
  &origins=40.6655101%2C-73.89188969999998
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101%2C-73.89188969999998&destinations=enc%3A_kjwFjtsbMt%60EgnKcqLcaOzkGari%40naPxhVg%7CJjjb%40cqLcaOzkGari%40naPxhV%3A&key=YOUR_API_KEY'

Traffic information

Traffic information is used when all the following apply (these are the conditions required to receive the duration_in_traffic field in the Distance Matrix response):

  • The travel mode parameter is driving , or is not specified ( driving is the default travel mode).
  • The request includes a valid departure_time parameter . The departure_time can be set to the current time or some time in the future. It cannot be in the past.

Optionally, you can include the traffic_model parameter in your request to specify the assumptions to use when calculating time in traffic.

The following URL initiates a Distance Matrix request for driving distances between Boston, MA or Charlestown, MA, and Lexington, MA and Concord, MA. The request includes a departure time, meeting all the requirements to return the duration_in_traffic field in the Distance Matrix response.

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?departure_time=now
  &destinations=Lexington%2CMA%7CConcord%2CMA
  &origins=Boston%2CMA%7CCharlestown%2CMA
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Boston%2CMA%7CCharlestown%2CMA&destinations=Lexington%2CMA%7CConcord%2CMA&departure_time=now&key=YOUR_API_KEY'

JSON

{
  "destination_addresses": ["Lexington, MA, USA", "Concord, MA, USA"],
  "origin_addresses": ["Boston, MA, USA", "Charlestown, Boston, MA, USA"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "33.3 km", "value": 33253 },
              "duration": { "text": "27 mins", "value": 1620 },
              "duration_in_traffic": { "text": "34 mins", "value": 2019 },
              "status": "OK",
            },
            {
              "distance": { "text": "41.5 km", "value": 41491 },
              "duration": { "text": "33 mins", "value": 1981 },
              "duration_in_traffic": { "text": "39 mins", "value": 2342 },
              "status": "OK",
            },
          ],
      },
      {
        "elements":
          [
            {
              "distance": { "text": "31.1 km", "value": 31100 },
              "duration": { "text": "26 mins", "value": 1543 },
              "duration_in_traffic": { "text": "29 mins", "value": 1754 },
              "status": "OK",
            },
            {
              "distance": { "text": "39.3 km", "value": 39338 },
              "duration": { "text": "32 mins", "value": 1904 },
              "duration_in_traffic": { "text": "35 mins", "value": 2077 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

XML


 OK
 Boston, MA, USA
 Charlestown, Boston, MA, USA
 Lexington, MA, USA
 Concord, MA, USA
 
  
   OK
   
    1620
    27 mins
   
   
    33253
    33.3 km
   
   
    2018
    34 mins
   
  
  
   OK
   
    1981
    33 mins
   
   
    41491
    41.5 km
   
   
    2342
    39 mins
   
  
 
 
  
   OK
   
    1543
    26 mins
   
   
    31100
    31.1 km
   
   
    1759
    29 mins
   
  
  
   OK
   
    1904
    32 mins
   
   
    39338
    39.3 km
   
   
    2077
    35 mins
   
  
 

Location Modifiers

You can use location modifiers to indicate how drivers should approach a particular location, by using the side_of_road modifier to specify which side of the road to use, or by specifying a heading to indicate the correct direction of travel.

Specify that calculated routes must pass through a particular side of the road

When specifying a location, you can request that the calculated route go through whichever side of the road the waypoint is biased towards by using the side_of_road: prefix. For example, this request will return the distance for a long route so that the vehicle ends on the side of the road to which the waypoint was biased:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=side_of_road%3A37.7663444%2C-122.4412006
  &origins=37.7680296%2C-122.4375126
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=37.7680296%2C-122.4375126&destinations=side_of_road%3A37.7663444%2C-122.4412006&key=YOUR_API_KEY'

When using side_of_road: with encoded polylines, the modifier is applied to every location along the polyline. For example, the two destinations in this request both use the parameter:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=side_of_road%3Aenc%3A%7BoqeF%60fejV%5BnC%3A
  &origins=San%20Francisco%20City%20hall
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=San%20Francisco%20City%20hall&destinations=side_of_road%3Aenc%3A%7BoqeF%60fejV%5BnC%3A&key=YOUR_API_KEY'

The side_of_road: modifier may only be used with this restriction:

  • The travel mode parameter is driving , or is not specified ( driving is the default travel mode).

Specify that calculated routes should have a particular heading

When specifying a location, you can request that the calculated route go through the location in a particular heading. This heading is specified with the prefix heading=X: , where X is an integer degree value between 0 (inclusive) and 360 (exclusive). A heading of 0 indicates North, 90 indicates East, continuing clockwise. For example, in this request the calculated route goes east from the origin, then takes a U-turn:

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=37.773245%2C-122.469502
  &origins=heading%3D90%3A37.773279%2C-122.468780
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=heading%3D90%3A37.773279%2C-122.468780&destinations=37.773245%2C-122.469502&key=YOUR_API_KEY'

The heading=X: modifier may only be used with these restrictions:

  • The travel mode parameter is driving , bicycling , or is not specified ( driving is the default travel mode).
  • The side_of_road modifier is not specified for the same location.
  • The location is specified with a latitude/longitude value. You may not use heading with addresses, Place IDs, or encoded polylines.

Distance Matrix request and responses

A sample HTTP request is shown below, requesting distance and duration from Vancouver, BC, Canada and from Seattle, WA, USA, to San Francisco, CA, USA and to Victoria, BC, Canada.

URL

https://maps.googleapis.com/maps/api/distancematrix/json
  ?destinations=San%20Francisco%7CVictoria%20BC
  &language=fr-FR
  &mode=bicycling
  &origins=Vancouver%20BC%7CSeattle
  &key=YOUR_API_KEY

локон

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver%20BC%7CSeattle&destinations=San%20Francisco%7CVictoria%20BC&mode=bicycling&language=fr-FR&key=YOUR_API_KEY'

This request will return four elements - two origins times two destinations:

Vancouver to San Francisco Ванкувер — Виктория
Seattle to San Francisco Seattle to Victoria

Results are returned in rows, each row containing one origin paired with each destination.

JSON

{
  "destination_addresses":
    ["San Francisco, Californie, États-Unis", "Victoria, BC, Canada"],
  "origin_addresses":
    ["Vancouver, BC, Canada", "Seattle, Washington, États-Unis"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "1 712 km", "value": 1711765 },
              "duration": { "text": "3 jours 16 heures", "value": 318119 },
              "status": "OK",
            },
            {
              "distance": { "text": "140 km", "value": 139695 },
              "duration": { "text": "6 heures 49 minutes", "value": 24567 },
              "status": "OK",
            },
          ],
      },
      {
        "elements":
          [
            {
              "distance": { "text": "1 452 km", "value": 1451704 },
              "duration": { "text": "3 jours 2 heures", "value": 266680 },
              "status": "OK",
            },
            {
              "distance": { "text": "146 km", "value": 146500 },
              "duration": { "text": "2 heures 53 minutes", "value": 10374 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

XML


 OK
 Vancouver, BC, Canada
 Seattle, Washington, États-Unis
 San Francisco, Californie, États-Unis
 Victoria, BC, Canada
 
  
   OK
   
    318119
    3 jours 16 heures
   
   
    1711765
    1712 km
   
  
  
   OK
   
    24567
    6 heures 49 minutes
   
   
    139695
    140 km
   
  
 
 
  
   OK
   
    266680
    3 jours 2 heures
   
   
    1451704
    1452 km
   
  
  
   OK
   
    10374
    2 heures 53 minutes
   
   
    146500
    146 km
   
  
 

DistanceMatrixResponse

Поле Необходимый Тип Описание
необходимый Array<string>

An array of addresses as returned by the API from your original request. As with origin_addresses , these are localized if appropriate. This content is meant to be read as-is. Don't programmatically parse the formatted addresses.

необходимый Array<string>

An array of addresses as returned by the API from your original request. These are formatted by the geocoder and localized according to the language parameter passed with the request. This content is meant to be read as-is. Don't programmatically parse the formatted addresses.

необходимый Array< DistanceMatrixRow >

An array of elements, which in turn each contain a status , duration , and distance element.

See DistanceMatrixRow for more information.

необходимый DistanceMatrixStatus

Contains the status of the request, and may contain debugging information to help you track down why the request failed.

See DistanceMatrixStatus for more information.

необязательный нить

A string containing the human-readable text of any errors encountered while the request was being processed.

DistanceMatrixStatus

Status codes returned by service.

  • OK indicates the response contains a valid result.
  • INVALID_REQUEST indicates that the provided request was invalid.
  • MAX_ELEMENTS_EXCEEDED indicates that the product of origins and destinations exceeds the per-query limit.
  • MAX_DIMENSIONS_EXCEEDED indicates that the number of origins or destinations exceeds the per-query limit.
  • OVER_DAILY_LIMIT indicates any of the following:
    • The API key is missing or invalid.
    • Billing has not been enabled on your account.
    • A self-imposed usage cap has been exceeded.
    • The provided method of payment is no longer valid (for example, a credit card has expired).
  • OVER_QUERY_LIMIT indicates the service has received too many requests from your application within the allowed time period.
  • REQUEST_DENIED indicates that the service denied use of the Distance Matrix service by your application.
  • UNKNOWN_ERROR indicates a Distance Matrix request couldn't be processed due to a server error. The request may succeed if you try again.

DistanceMatrixRow

Поле Необходимый Тип Описание
необходимый Array< DistanceMatrixElement >

When the Distance Matrix API returns results, it places them within a JSON rows array. Even if no results are returned (such as when the origins and/or destinations don't exist), it still returns an empty array.

Rows are ordered according to the values in the origin parameter of the request. Each row corresponds to an origin, and each element within that row corresponds to a pairing of the origin with a destination value.

Each row array contains one or more element entries, which in turn contain the information about a single origin-destination pairing.

See DistanceMatrixElement for more information.

DistanceMatrixElement

Поле Необходимый Тип Описание
необходимый DistanceMatrixElementStatus

A status for the element.

See DistanceMatrixElementStatus for more information.

необязательный TextValueObject

The total distance of this route, expressed in meters (value) and as text. The textual value uses the unit system specified with the unit parameter of the original request, or the origin's region.

See TextValueObject for more information.

необязательный TextValueObject

The length of time it takes to travel this route, expressed in seconds (the value field) and as text. The textual representation is localized according to the query's language parameter.

See TextValueObject for more information.

необязательный TextValueObject

The length of time it takes to travel this route, based on current and historical traffic conditions. See the traffic_model request parameter for the options you can use to request that the returned value is optimistic, pessimistic, or a best-guess estimate. The duration is expressed in seconds (the value field) and as text. The textual representation is localized according to the query's language parameter. The duration in traffic is returned only if all of the following are true:

  • The request includes a departure_time parameter.
  • Traffic conditions are available for the requested route.
  • The mode parameter is set to driving.

See TextValueObject for more information.

необязательный Стоимость проезда

If present, 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.

See Fare for more information.

Стоимость проезда

The total fare for the route.

{
  "currency" : "USD",
  "value" : 6,
  "text" : "$6.00"
}
Поле Необходимый Тип Описание
необходимый нить

An ISO 4217 currency code indicating the currency that the amount is expressed in.

необходимый нить

The total fare amount, formatted in the requested language.

необходимый число

The total fare amount, in the currency specified.

DistanceMatrixElementStatus

  • OK indicates the response contains a valid result.
  • NOT_FOUND indicates that the origin and/or destination of this pairing couldn't be geocoded.
  • ZERO_RESULTS indicates no route could be found between the origin and destination.
  • MAX_ROUTE_LENGTH_EXCEEDED indicates the requested route is too long and cannot be processed.

TextValueObject

An object containing a numeric value and its formatted text representation.

Поле Необходимый Тип Описание
необходимый нить

String value.

необходимый число

Numeric value.