Данные о дорогах в реальном времени позволяют получать актуальную информацию о состоянии дорог и событиях на выбранных маршрутах, что обеспечивает динамический мониторинг и быстрое реагирование. Эти данные отличаются от периодически собираемых данных, доступных в BigQuery, и подходят для сценариев, требующих своевременной информации.
Эти данные передаются непрерывно и включают продолжительность поездки, которая указывает время в пути по маршруту, и интервалы считывания скорости, которые показывают плотность движения по маршруту.
Чтобы получить доступ к данным о дорогах в реальном времени, в ваш контракт должен быть включен пакет Real-Time Operations.
Как создать подписку Pub/Sub на интервалы считывания продолжительности поездки и скорости
Вам будут предоставлены специальные темы Google Cloud Pub/Sub, в которых вы сможете подписаться на данные в реальном времени для всех созданных вами маршрутов.
В приведенном ниже примере кода показан формат темы с использованием двоичного кодирования:
projects/maps-platform-roads-management/topics/rmi-roadsinformation-PROJECT_NUMBER
Мы также предоставляем ещё одну тему с кодировкой JSON (с суффиксом -json). Чтобы получать сообщения с данными в реальном времени, необходимо подписаться на предоставленную вам тему издателя-подписчика. О том, как подписаться на тему Cloud Pub/Sub и получать из нее сообщения, рассказывается в статье Как подписаться на тему.
Схема интервалов продолжительности поездки и скорости чтения
Каждое сообщение с данными в реальном времени содержит следующую информацию:
- Сведения о дорогах, например
duration_in_seconds,static_duration_in_seconds,speed_reading_offsets(интервалы считывания скорости на основе смещения),retrieval_timestampиhas_road_closure. - Идентификаторы маршрутов, например
selected_route_idиdisplay_name.
Каждое сообщение публикуется в формате Protobuf, как показано ниже.
syntax = "proto3"; // Contains the road information like travel duration and speed reading // intervals for a selected route. message RoadsInformation { // Legacy message. May stop being populated on or after November 9, 2026. // Use top-level duration_in_seconds and static_duration_in_seconds instead. message TravelDuration { // The duration of travel through the route based on current road // conditions. float duration_in_seconds = 1; // The duration of travel through the route without taking road // conditions into consideration. float static_duration_in_seconds = 2; } message Timestamp { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. int64 seconds = 1; // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. int32 nanos = 2; } // Legacy message representing the latitude and longitude of a coordinate // within a coordinate-based speed reading interval. message LatLng { float latitude = 1; float longitude = 2; } // Legacy coordinate-based speed reading interval message. May stop being // populated on or after November 9, 2026. Use SpeedReadingOffset instead. message SpeedReadingInterval { // The coordinates on the polyline for the speed reading interval. repeated LatLng interval_coordinates = 1; // Describes the categorized current speed of road conditions. // Possible values are: // - "NORMAL": Road is flowing smoothly, no slowdown is detected. // - "SLOW": Slowdown detected, but no congestion formed. // - "TRAFFIC_JAM": Traffic jam detected. In this legacy field, heavy // traffic jams (dark red) are also reported as "TRAFFIC_JAM"; // "TRAFFIC_JAM_HEAVY" is never used. string speed = 2; } // Offset-based speed reading interval along the route. message SpeedReadingOffset { // The distance offset from the start of the route in meters for the start // of the interval (inclusive). int32 start_offset = 1; // The distance offset from the start of the route in meters for the end of // the interval (exclusive; equals the start_offset of the subsequent // interval). int32 end_offset = 2; // Describes the categorized current speed of traffic, aligned with the // colors in the Google Maps traffic layer. Possible values are: // - "NORMAL" (green): Traffic is flowing smoothly, no slowdown is detected. // - "SLOW" (yellow): Slowdown detected, but no traffic jam formed. // - "TRAFFIC_JAM" (red): Traffic jam detected. // - "TRAFFIC_JAM_HEAVY" (dark red): Heavy traffic jam detected (available // as of October 8, 2026). string speed = 3; } // Id for selected_route. string selected_route_id = 1; // User provided name for the route. string display_name = 2; // Legacy coordinate-based speed reading intervals. May stop being populated // on or after November 9, 2026. Use speed_reading_offsets instead. repeated SpeedReadingInterval speed_reading_intervals = 3; // Legacy travel time information. May stop being populated on or after // November 9, 2026. Use duration_in_seconds and static_duration_in_seconds // instead. TravelDuration travel_duration = 4; // Legacy timestamp when the road data was collected. May stop being populated // on or after November 9, 2026. Use retrieval_timestamp instead. Timestamp retrieval_time = 5; // Contains a geojson polyline representing the optimal route determined // based on user's input waypoints. string route_geometry = 6; // Road segment place IDs along the route. They follow topological order // and are always connected. repeated string road_segment_ids = 7; // Offset-based speed reading intervals representing traffic density across // the route; each interval is demarcated by the distance offset from the // start of the route. Omitted when has_road_closure is true. repeated SpeedReadingOffset speed_reading_offsets = 8; // The duration of travel through the route based on current traffic // conditions. Omitted when has_road_closure is true. float duration_in_seconds = 9; // The duration of travel through the route without taking traffic // conditions into consideration. float static_duration_in_seconds = 10; // The time the traffic data was collected, as an RFC 3339 UTC timestamp // string (for example, "2026-10-08T15:04:05+00:00"). string retrieval_timestamp = 11; // Whether there is a full road closure on the route. When true, // duration_in_seconds and speed_reading_offsets are omitted because the // route is impassable. Omitted when road closure information is undetermined. bool has_road_closure = 12; }
Интервалы считывания скорости на основе смещения и перенос полей
С 8 октября 2026 г. интервалы скорости предоставляются в поле speed_reading_offsets, где каждый интервал разграничивается значениями start_offset (включительно) и end_offset (исключительно) в метрах от начала маршрута и включает четвертую категорию скорости TRAFFIC_JAM_HEAVY. Подробную информацию о категориях скорости и форматах интервалов можно найти в разделе Интервалы скорости чтения.
В таблице ниже показано, какие поля устаревшего издателя-подписчика (которые могут перестать заполняться 9 ноября 2026 г. или позже) чем заменяются.
| Устаревшее поле | Поле замены | Примечания |
|---|---|---|
speed_reading_intervals |
speed_reading_offsets |
Использует смещения в метрах (start_offset, end_offset) вместо координат ломаной линии и добавляет категорию скорости TRAFFIC_JAM_HEAVY. |
travel_duration.duration_in_seconds |
duration_in_seconds |
Преобразуется в поле float верхнего уровня. |
travel_duration.static_duration_in_seconds |
static_duration_in_seconds |
Преобразуется в поле float верхнего уровня. |
retrieval_time |
retrieval_timestamp |
Форматируется как строка RFC 3339, которую подписки BigQuery автоматически преобразуют в TIMESTAMP. |
Потоковая передача данных о маршрутах в BigQuery с помощью издатель-подписчик
Вы можете настроить подписку Pub/Sub для передачи данных о дорогах непосредственно в таблицу BigQuery. Это позволяет надежно хранить данные и проводить мощный анализ предоставленной информации о маршруте. Прежде чем настраивать подписку этого типа, создайте в проекте BigQuery подходящий набор данных и таблицу для записи данных.
Подробные инструкции о том, как создать подписку Pub/Sub, которая записывает данные в BigQuery, приведены в статье Потоковая передача данных в BigQuery.
Создайте подписку BigQuery на тему в кодировке JSON. При настройке подписки выберите Использовать схему таблицы и включите Удалять неизвестные поля, чтобы конвейер передачи данных продолжал работать без сбоев при добавлении новых полей. Чтобы хранить новые поля, например speed_reading_offsets, добавьте в таблицу соответствующие столбцы.
Схема таблицы BigQuery
Сообщения, опубликованные в теме Pub/Sub, которые также могут быть записаны в таблицу BigQuery, соответствуют следующей схеме. Используйте эту схему при создании целевой таблицы BigQuery, чтобы обеспечить совместимость.
[ { "mode": "NULLABLE", "name": "selected_route_id", "type": "STRING", "description": "Id for selected_route." }, { "mode": "NULLABLE", "name": "display_name", "type": "STRING", "description": "User provided name for the route." }, { "fields": [ { "mode": "NULLABLE", "name": "speed", "type": "STRING", "description": "Describes the categorized current speed of traffic. Possible values are: \"NORMAL\": Traffic is flowing smoothly, no slowdown is detected. \"SLOW\": Slowdown detected, but no traffic jam formed. \"TRAFFIC_JAM\": Traffic jam detected (groups red and dark red segments; does not include \"TRAFFIC_JAM_HEAVY\")." }, { "fields": [ { "mode": "NULLABLE", "name": "latitude", "type": "NUMERIC" }, { "mode": "NULLABLE", "name": "longitude", "type": "NUMERIC" } ], "mode": "REPEATED", "name": "interval_coordinates", "type": "RECORD", "description": "The geometry for this interval" } ], "mode": "REPEATED", "name": "speed_reading_intervals", "type": "RECORD", "description": "Legacy coordinate-based speed reading intervals. May stop being populated on or after November 9, 2026. Use speed_reading_offsets instead." }, { "fields": [ { "mode": "NULLABLE", "name": "duration_in_seconds", "type": "FLOAT", "description": "The duration of travel through the route based on\ncurrent traffic conditions." }, { "mode": "NULLABLE", "name": "static_duration_in_seconds", "type": "FLOAT", "description": "The duration of travel through the route without\ntaking traffic conditions into consideration." } ], "mode": "NULLABLE", "name": "travel_duration", "type": "RECORD", "description": "Legacy travel time information. May stop being populated on or after November 9, 2026. Use top-level duration_in_seconds and static_duration_in_seconds instead." }, { "fields": [ { "mode": "NULLABLE", "name": "seconds", "type": "INTEGER", "description": "Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive." }, { "mode": "NULLABLE", "name": "nanos", "type": "INTEGER", "description": "Non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanos values that count forward in time. Must be from 0 to 999,999,999 inclusive." } ], "mode": "NULLABLE", "name": "retrieval_time", "type": "RECORD", "description": "Legacy timestamp when the traffic data was collected. May stop being populated on or after November 9, 2026. Use retrieval_timestamp instead." }, { "mode": "NULLABLE", "name": "route_geometry", "type": "STRING", "description": "Contains a geojson polyline representing the optimal route determined based on user's input waypoints" }, { "mode": "REPEATED", "name": "road_segment_ids", "type": "STRING", "description": "Road segment place IDs along the route. They follow topological order and are always connected" }, { "fields": [ { "mode": "NULLABLE", "name": "start_offset", "type": "INTEGER", "description": "The distance offset from the start of the route in meters for the start of the interval (inclusive)." }, { "mode": "NULLABLE", "name": "end_offset", "type": "INTEGER", "description": "The distance offset from the start of the route in meters for the end of the interval (exclusive; equals the start_offset of the subsequent interval)." }, { "mode": "NULLABLE", "name": "speed", "type": "STRING", "description": "Describes the categorized current speed of traffic, aligned with the colors in the Google Maps traffic layer. Possible values are: \"NORMAL\" (green): Traffic is flowing smoothly, no slowdown is detected. \"SLOW\" (yellow): Slowdown detected, but no traffic jam formed. \"TRAFFIC_JAM\" (red): Traffic jam detected. \"TRAFFIC_JAM_HEAVY\" (dark red): Heavy traffic jam detected (available as of October 8, 2026)." } ], "mode": "REPEATED", "name": "speed_reading_offsets", "type": "RECORD", "description": "Offset-based speed reading intervals representing traffic density across the route; each interval is demarcated by the distance offset from the start of the route. Omitted when has_road_closure is true." }, { "mode": "NULLABLE", "name": "duration_in_seconds", "type": "FLOAT", "description": "The duration of travel through the route based on current traffic conditions. Omitted when has_road_closure is true." }, { "mode": "NULLABLE", "name": "static_duration_in_seconds", "type": "FLOAT", "description": "The duration of travel through the route without taking traffic conditions into consideration." }, { "mode": "NULLABLE", "name": "retrieval_timestamp", "type": "TIMESTAMP", "description": "The time the traffic data was collected." }, { "mode": "NULLABLE", "name": "has_road_closure", "type": "BOOLEAN", "description": "Whether there is a full road closure on the route. When true, duration_in_seconds and speed_reading_offsets are omitted because the route is impassable. A NULL value indicates that road closure information is undetermined." } ]