ある場所のリアルタイムの交通状況を取得します

目的: HERE Traffic フローカタログからリアルタイムトラフィックを取得します。

複雑さ: 初心者向け

前提条件: 資格情報を取得し、資格情報を確認します

所要時間: 30 分

ソースコード: ダウンロード

このチュートリアルで は、 HERE Traffic フロー カタログについて説明し、このカタログを使用して交通状況データについての情報を取得する方法を示します。

このチュートリアルでは、次のトピックについて説明します。

HERE Traffic フローカタログの概要

HERE Traffic フロー カタログは、ドライバーがストレスのない方法で効率的に目的地に到着できるよう支援します。 カタログでは、交通状況や、通常よりも遅い交通状況、道路工事、事故など、遅延の原因となる可能性のある事故についての最新情報を提供しています。 さらに、高速道路や動脈の交通状況を表示することができ、交通状況を把握できる到着予定時間( ETA )を計算するための要素となります。

リアルタイムの交通データは、高品質でリッチな車両センサデータなど、複数のソースを集約して分析する洗練されたモデルによって生成されます。 その結果、実際の交通状況を正確に再現できます。

HERE Traffic フロー カタログを使用すると、最大規模の集約リアルタイムデータベースの 1 つにアクセスできる、より適切なトラフィック管理ソリューションを構築できます。

次の図は、平均速度と紙詰まり係数に関する情報を含むリアルタイムのトラフィックを示しています。

カタログ情報を取得します

HERE Traffic Flow は、道路状況をライブで描写する公開カタログです。 交通渋滞を特定し、道路状況や事故に関するライブ情報をドライバーに提供できます。

基本的なカタログ情報を取得するには 、プラットフォームポータルを使用 するか、または次の CLI コマンドを実行します。

olp catalog show hrn:here:data::olp-here:here-traffic-flow-v2

出力には、次の情報が含まれている必要があります。

ID                       here-traffic-flow-v2
name                     HERE Traffic Flow (new)
HRN                      hrn:here:data::olp-here:here-traffic-flow-v2
summary                  "HERE RealTime Traffic Flow" provides live information on traffic conditions on roadways.
description              "HERE RealTime Traffic Flow" provides a live depiction of conditions on the road. It identifies where traffic congestion occurs, and how bad it is, delivering minute-by-minute information on road conditions that could set a driver back.

Real-time traffic data is produced by a sophisticated model that aggregates and analyzes a mix of sources, including high-quality rich vehicle sensor data.

The result: best-in-class accuracy in depicting real-world traffic conditions.
notifications enabled?   false
tags                     TrafficItem, TrafficItems, flow, traffic, RealtimeTraffic
billing tags             10648TAppsProd
created                  2022-02-11T21:10:59.475863Z
owner                    HERE-e64d84b3-556e-4f69-ac85-e615cc2c2cab, olp-here
config version           4
metadata version         -1
metadata minimum version -1
marketplace ready        false
layers                   
type         ID                                 name
volatile     realtime-traffic-flow-volatile     RealTime Traffic Flow (v2)
replication              
role                ID             
primary             eu-ireland

出力に基づい て、 HERE Traffic フローが 1 つのレイヤーで構成されていることがわかります。 RealTime Traffic Flow (v2) このレイヤーは、道路の現在の交通速度を提供します。 HERE Traffic を搭載し、 1 分ごとに速度が更新されます。

次のチュートリアルで realtime-traffic-flow-volatile は、レイヤーを使用してリアルタイムトラフィックに関する情報を取得します。 realtime-traffic-flow-volatile レイヤーについて学習しましょう。

realtime-traffic-flow-volatile プラットフォームポータルでレイヤーをチェックアウト するか、次の OLP CLI コマンドを実行して、レイヤーに関する情報を取得します。

olp catalog layer show hrn:here:data::olp-here:here-traffic-flow-v2 realtime-traffic-flow-volatile

出力には、次の情報が含まれている必要があります。

Details of the realtime-traffic-flow-volatile layer:

ID                  realtime-traffic-flow-volatile
name                RealTime Traffic Flow (v2)
summary             RealtimeFlow 3.3
description         The traffic flow layer provides the current speed of traffic on roads. Powered by HERE Traffic, the speeds are updated every minute.

Each tile contains Protobuf data, which is a list of all the current traffic flow messages based on the Traffic schema. Any message which spans across multiple tiles will be reported in all tiles where it exists, with the same ID.
layerType           volatile
partitioning        heretile, tile levels: 12
partitioningScheme  heretile
volume              volatile
contentType         application/x-protobuf
schema              hrn:here:schema::olp-here:com.here.traffic.realtime:traffic_v2:2.1.15
tags                TOLP
billingTags         10648TAppsProd
coverage            US
created             2022-02-11T21:35:45.216436Z
volatileProperties  {"dataRedundancy":"multi-instance","storageCapacityMb":21000}
TTL                 3600000

明らか volatile に、レイヤーはタイプになっています。つまり、新しいデータが存在するたびに古いデータが上書きされます。 realtime-traffic-flow-volatile レイヤー内の情報は毎分更新されます。 レイヤーには次のプロパティがあります。

  • partitioning および partitioningScheme: : レイヤー heretileはタイルレベルにあり 12ます。 この種類のタイリング を使用すると、タイルでのタイルの検索など、地理的に関連するタスクを簡単に実行できます。詳細については、バウンディング ボックス ID の計算のチュートリアルを参照してください。 タイルの詳細について Java APIは、『ロケーション ライブラリ開発者ガイド』の [TIONS | Scala API ] HereTileResolverクラスを参照してください。
  • contentType:- application/x-protobuf このコンテンツタイプでは、タイルは Protobuf 形式でエンコードされます。
  • schema: traffic_v2 プラットフォームに保存されているデータをデコードするために使用されます。 traffic_v2 スキーマの詳細について Use Data Schema は、の章を参照してください。
  • coverage 61 国をカバーするrealtime-traffic-flow-volatileレイヤーが表示 され、ISO 3166国の 2 文字のコードのリストとして値が表示されます。

上記のプロパティの詳細については、を参照 Data User Guideしてください。

データスキーマを使用します

Real-Time Traffic スキーマは、特定の道路セグメントの交通状況を表します。

traffic_v2 レイヤーに保存されているデータは traffic_v2 、 Protobuf スキーマ を使用してエンコードされます。 traffic_v2 Protobuf スキーマ は、 HERE Traffic フローのさまざまなデータ層で使用されるプロトコルバッファメッセージおよび列挙体を定義します。 メッセージ定義は、カタログレイヤー内のパーティション の構造を記述する対応する .proto ファイルで定義されます。

リアルタイムの交通状況は 、詳細な位置情報グリッドの属性(average_speed_kphjam_factorなど)として提供されます。 HERE は、その場所を記述するため HERE tiling に、レベルで適切に定義 12された場所を使用します。

データの構造について詳しく見ていきましょう。

traffic_v2 に は、flowlanesegmentspeedおよびtraversabilityの各ステータス項目が含まれています。

Flow メッセージには、 1 つ以上の道路セグメントの交通速度に関する情報が含まれています。 フローに含まれるセグメントは、 HERE platform のアルゴリズムによって決定されます。 このメッセージには Segment 、複数のメッセージを含めることができます。 この場合、セグメントは道路の接続されたセクションを表し、走行方向に並べられます。 Flow メッセージ内のconfidence属性は、速度計算で使用されたリアルタイムデータの割合を示します。ここで、次のようになります。

  • 0.75 が以上の場合は、信頼性の高いリアルタイム情報を示します
  • 値が 0.5 過去 0.7 の速度範囲にある場合、トラフィック速度の計算に使用されます
  • 値が 0.0 ~ の範囲にある場合 0.5 、制限速度を使用してトラフィックの速度が計算されます
  • 値が -1 - の場合、道路は閉鎖されます。

Segment このメッセージには、道路の一部での交通の流れに関する情報が含まれています。 まず、が Segment 何であるかを確認してみましょう。 A Segment は、 2 つ Nodes のをオプションの中間形状点と接続するダイレクトポリラインです。 の論理的な方向 Segment は、その開始 Node から終了までのものとして定義 Nodeされます。 この方向は、の移動方向とは関連 Segmentがありません。 ただし、進行方向や制限速度などの方向属性は Segments 、この論理的な方向を基準にしています。 与えられたNodeは 、 それに隣接する別のSegmentsNodeの開始と終了の両方である場合があります。 の詳細 Segmentsについては、を参照 Topology Modelしてください。

次の図は、HERE Map Contentカタログのtopology-geometryレイヤーを使用してNodesで接続されているSegmentsを示しています。

Segment メッセージには、 Speed メッセージを使用したこのセグメントの平均トラフィック速度に関する情報が記述されています。

Segment メッセージ内のjam_factor属性は、交通渋滞の状態を示し 、0.0から10.0までの範囲で、自由に交通が流れていることを示します。 Segment メッセージ内のstart_offset属性は、このセグメントの先頭からのオフセット比率をトラフィック条件全体に関連して記述します。

Segment メッセージには、セグメントが TraversabilityStatus メッセージを使用してトラフィックにオープンであるかどうかも記述されます。この場合、次の値が使用されます。 OPEN - セグメントがトラフィックに対してオープンで CLOSED ある場合、 - セグメントがトラフィックに対してクローズされている場合、 ROAD_NOT_ROUTABLE および - セグメントがトラフィックの伝送を制限されている場合。 建設中や重大な事故が発生した場合など、リバーシブル道路の両方向が閉じていると、このような状況になることがあります。

Segment メッセージで最後に使用されたメッセージは Lane 、道路の個々の車線の交通速度に関する情報を含むメッセージです。 このメッセージは、道路沿いに異なる車線速度がある場合にのみ表示されます。

メッセージ定義は次 flow.proto のファイルにあります。

syntax = "proto3";

package com.here.traffic.realtime.v2;

import "com/here/traffic/realtime/v2/LocationTypes.proto";

/**
The `Flow` message contains information about the speed of traffic on one or
more road segments. The segments contained by a flow are determined by
algorithms in the Open Location Platform.
*/
message Flow {
    /**
    One or more messages containing information about the flow of traffic on
    a section of roadway, or "segment". If a `Flow` message contains multiple
    `segment` messages, the segments represent
    connected sections of the roadway and are ordered in the driving direction.
    Each `segment` contains a start_offset field which defines the ratio of
    this segment to the overall Flow message. The congestion level for this
    segment is of value 1, i.e. CONSERVATIVE.
    */
    repeated Segment segment = 1;

    /**
    A number from 0.0 to 1.0 indicating the percentage of real-time data used
    in the speed calculation.
    You can use this field to identify whether the data for this `Flow` is
    derived from real-time probe sources or historical information only.
    Confidence is only available for the `Flow` message and applies to all
    `Segment` messages.

    - 0.71 to 1.0: Real-time speeds were used to calculate the traffic speed
    for the `Flow`. A value of 0.75 or greater indicates high confidence
    real-time information.

    - 0.5 to 0.7: Historical speeds were used to calculate the traffic
    speed for the `Flow`.

    - 0.0 to 0.5: The speed limit was used to calculate the speed of
    traffic for the `Flow`.

    - -1.0: The road is closed

    */
    double confidence = 2;

    /**
    DEPRECATED. Flow conditions for supplementary location reference,
    one for each applicable location type
    */
    repeated SupplementaryFlowCondition supplementary_flow_condition
        = 3 [deprecated = true];

    /**
    Additional segments for congestion levels 2 and 3.
    */
    repeated CongestionLevelCodedSegments congestion_level_coded_segments_list
        = 4;
}


/**
Congestion level Option specifies the desired level of “aggressiveness”
to represent the traffic condition.
The client can decide which CF element, if encoded, to utilize.
 */
enum CongestionLevelOption {
    UNKNOWN = 0;
    CONSERVATIVE = 1;
    MEDIUM_AGGRESSIVE = 2;
    MOST_AGGRESSIVE = 3;
}

/**
Segments coded according to congestion level option
 */
message CongestionLevelCodedSegments {
    //Congestion level option identifier
    CongestionLevelOption congestion_level_option = 1;
    //One or more segments for the congestion level
    repeated Segment segments = 2;
}

/**
The `Segment` message contains information about the flow of traffic on a
section of roadway.
*/
message Segment {
    /**
    Information about the speed of traffic for this segment.
    */
    Speed speed = 1;

    /**
    A number between 0.0 and 10.0 indicating how freely traffic is flowing.
    A value of 0 means traffic is flowing freely. A value of 10 means
    traffic is stopped.
    A value of -1.0 indicates that `jam_factor` could not be calculated.

    If a road is closed, `jam_factor` is 10.

    If a road is reversible and traffic is flowing opposite the driving direction,
    `jam_factor` is -1. This value is useful when displaying traffic on a map
    and you do not want to display the road as closed.
    */
    double jam_factor = 2;

    /**
    The offset ratio from the start of this segment in relation to the entire
    traffic condition.
    */
    double start_offset = 3;

    /**
    Specifies whether the segment is traversable.
    See `Flow.TraversabilityStatus` for valid values.
    */
    TraversabilityStatus traversability_status = 4;

    /**
    The traffic condition in each lane. The `lanes` field is only provided
    if there are different lane condition along a roadway.
    When there is lane-level traffic along a roadway, there will be two or
    more `Lane` messages in the `Segment`.
    */
    repeated Lane lanes = 5;

    //The junction traversability status.
    JunctionTraversabilityStatus junction_traversability_status = 6;

    //Length of the segment in km
    double segment_length_in_km = 7;

    //The lane type for this road segment
    BasicLaneType basic_lane_type = 8;

    //Trend of jam factor
    JamFactorTrend jam_factor_trend = 9;

    //Flow conditions and causes based on TFP
    TFPCode tfp_code = 10;

    /**
    Flow conditions and causes codes based on specification of TISA TPEG2-TFP_1.1
     */
    message TFPCode {
        //The tfp006 cause of the traffic flow.
        int32 cause_code = 1;

        //Status parameters per TFP specification.
        StatusParameters status_parameters = 2;

        //Statistical parameters per TFP specification.
        StatisticalParameters statistical_parameters = 3;

        //The vehicle restriction per TFP specification.
        Restrictions restriction = 4;
    }

    //At-grade junction traversability status. Used for road
    //closures to indicate if the closure can be crossed.
    enum JunctionTraversabilityStatus {
        UNKNOWN = 0;
        ALL_JUNCTIONS_CLOSED = 1;
        INTERMEDIATE_CLOSED_EDGE_OPEN = 2;
        ALL_JUNCTIONS_OPEN = 3;
    }

    /**
    The basic type of the lane.
    */
    enum BasicLaneType {
        //Regular traffic lane
        TRAFFIC_LANE = 0;
        //Express lane
        EXPRESS = 1;
        //Ramp lane
        RAMP = 2;
        //Entry lane;
        ENTRY = 3;
        //EXIT lane
        EXIT = 4;
    }

    /**
    The flow status parameters.
    */
    message StatusParameters {
        //The tfp003 Level Of Service code.
        int32 level_of_service = 1;
        //The achievable average speed in km/h.
        int32 average_speed_in_kmh = 2;
        //The time in seconds it takes to traverse the affected
        //road segment under free flow traffic conditions.
        int32 free_flow_travel_time_in_seconds = 3;
        //The delay on the road segment in seconds.
        int32 delay_in_seconds= 4;
    }

    /**
    The statistical parameters based on TISA TPEG2-TFP_1.1.
    */
    message StatisticalParameters {
        //The risk (%) that a congestion
        // (LOS level 'stationary traffic' or 'blocked') will occur
        // at this road section.
        int32 congestion_probability = 1;
        //TFP based value Used to determine the risk that the travel time
        // may exceed the expected travel time considerably.
        int32 t90_relative = 2;
        //The tfp008 flow data quality
        int32 flow_data_quality = 3;
        //This parameter may be used to link to a LOS prediction pattern.
        int32 prediction = 4;
    }

    /**
    tfp based information on restrictions related to the reported traffic flow
    */
    message Restrictions {
        //The tfp001 Vehicle class
        int32 vehicle_class_assignment = 1;
        //The tfp002 vehicle Credentials
        int32 vehicle_credentials = 2;
        //The tfp005 lane restrictions
        int32 lane_restriction = 3;
        //Angle of an entry/exit to the road stretch in 360/255 degree steps
        // clockwise to the direction of the road stretch at the entry/exit point
        int32 angle = 4;
        //Length affected in 10 meter steps
        int32 length_in_ten_meters_steps = 5;
    }

}

/**
   The `Speed` message contains information about the velocity of traffic
   traveling along the segment.
   */
message Speed {

    /**
    The average speed that traffic is traveling, in Kilometers per hour.
    A value of -1.0 indicates that the average speed could not be calculated.
    */
    double average_speed_kph = 1;

    /**
    The average speed that traffic is traveling, but limited to the speed limit.
    If the traffic speed is greater than the speed limit, the value of this
    field will be the speed limit instead of the actual
    traffic speed. The speed is in in Kilometers per hour.

    A value of -1.0 indicates that the average speed could not be calculated.
    */
    double average_speed_capped_kph = 2;

    /**
    The speed at which vehicles can travel the segment when there is no traffic
    congestion or other impediments such as a road closure.
    This speed is calculated as the 80th percentile of observed speeds
    during non-rush hour periods.

    Free flow is useful for understanding the level of congestion.
    When the average speed is greater than or equal to the free flow speed,
    it can be assumed that there is no traffic congestion.
    */
    double free_flow_speed_kph = 3;
}

/**
The `TraversablityStatus` field indicates whether a segment is open to traffic.

- `OPEN`: The segment is open for traffic. This includes reversible roads
that are open.
- `CLOSED`: The segment is closed to traffic. No `Speed` messages will be
provided for this segment.
- `ROAD_NOT_ROUTABLE`: The segment is restricted from carrying traffic.
In some situations, portions of a reversible road will be marked as CLOSED
rather than ROAD_NOT_ROUTABLE. This can happen when both directions of the
reversible road are closed, such as for construction or major accidents.
In a map display, we recommend that you use ROAD_NOT_ROUTABLE to indicate that
the road is not routable, the road segment is not drivable, and not to show
traffic on this roadway.
*/
enum TraversabilityStatus {
    OPEN = 0;
    CLOSED = 1;
    ROAD_NOT_ROUTABLE = 2;
}

/**
Trend of Jam Factor
 */
enum JamFactorTrend {
    CONSTANT_CONGESTION = 0;
    DECREASING_CONGESTION = 1;
    RAPIDLY_DECREASING_CONGESTION = 2;
    INCREASING_CONGESTION = 3;
    RAPIDLY_INCREASING_CONGESTION = 4;
}

/**
The `Lane` message contains information about the speed of traffic in individual
lanes in a roadway.  A `Lane` message is only provided if there are different
lane speeds along a roadway.

The number of lanes along a roadway can be determined by looking at the maximum
lane number in all `Lane` messages in the segment.
*/
message Lane {

    /**
    A list of lanes associated with the traffic. Lane numbers use the HERE Map
    method of lane numbering where the left lane is 1 and each lane to the
    right of the left lane is numbered sequentially. For example, in a
    three-lane road, the left lane is 1, the center lane is 2, and the right
    lane is 3. Lane 1 is always the left lane, regardless of the driving side.
    If multiple lane numbers are presented, all lanes will have the traffic
    condition. Lane numbers will always be sequential.
    */
    repeated int32 lane_number = 1;

    /**
    A Flow.Speed message containing the traffic speed for this lane.
    */
    Speed speed = 2;

    /**
    The jam factor for this `Lane`. See `jam_factor` field in `Segment` message
    for definition.
    */
    double jam_factor = 3;

    //Additional lane type information
    SpecialtyLaneType lane_type = 4;

    //More granular trend information of jam factor
    JamFactorTrend jam_factor_trend = 5;

    //Zero or more arterial turn lane information
    repeated ArterialTurnLane arterial_turn_lanes = 6;

    /**
    Specialty lane types
    */
    enum SpecialtyLaneType {
        REGULAR = 0;
        HOV = 1;
        ARTERIAL_TURN = 2;
    }

    /**
    ArterialTurnLane message is provided if there are one or more Arterial Turn Lane
    events associated with this lane.
     */
    message ArterialTurnLane {

        //To Bearing is the bearing associated with the Arterial Turn
        //Lane maneuver. Bearing is the relative angle (degrees 0-359)
        //based on the link prior to intersection and the successor link
        //after the maneuver. For example, a right turn is represented
        //by TB=90, straight is TB=0, and left turn is TB=270.
        int32 to_bearing = 1;

        //To LinkID is the successor linkID associated with the
        //maneuver. The linkID will be in driving direction order; “F”
        //represents travel direction FROM reference node, “T”
        //represents travel direction TO reference node.
        string to_here_map_link_id = 2;

        //The extra delay in seconds that corresponds to the maneuver.
        //This delay time is extra delay in addition to the the time of
        //the speed reported at segment level.
        int32 extra_delay_in_seconds = 3;

        //The average speed, not capped by speed limit, on these lanes
        //of traffic that current traffic is travelling.
        double average_speed_in_kph = 4;

        //The number between 0.0 and 10.0 indicating the expected
        //quality of travel.
        double jam_factor = 5;

    }

}

Maven プロジェクトを設定します

リアルタイムの交通状況を取得するには、チュートリアルの冒頭でソースコードをダウンロードして任意のフォルダーに保存するか、次のようにプロジェクトのフォルダー構造を最初から作成します。

here-realtime-traffic
└── src
    └── main
        ├── java
        └── resources
        └── scala

この操作は、次の bash 1 つのコマンドで実行できます。

mkdir -p here-realtime-traffic/src/main/{java,resources,scala}

Maven POM ファイルは Maven 設定の確認 チュートリアルのファイルと似ていますが、親の POM および依存関係のセクションが更新されています。

親 POM sdk-standalone-bom_2.12 は、このチュートリアルを簡単にするためにローカルで実行できるように設計されているためです。

<parent>
    <groupId>com.here.platform</groupId>
    <artifactId>sdk-standalone-bom_2.12</artifactId>
    <version>2.54.3</version>
    <relativePath/>
</parent>

次の依存関係が使用されます。

  • hrn_2.12 リアルタイムトラフィックカタログ HERE リソースネーム を初期化します。
  • traffic_v2_java パーティションデータをデコードします。
  • data-client_2.12 data-engine_2.12 パーティション データをダウンロードできます。

依存関係 :

<dependencies>
    <dependency>
        <groupId>com.here.platform.data.client</groupId>
        <artifactId>data-client_${scala.compat.version}</artifactId>
    </dependency>
    <dependency>
        <groupId>com.here.platform.data.client</groupId>
        <artifactId>data-engine_${scala.compat.version}</artifactId>
    </dependency>
    <dependency>
        <groupId>com.here.hrn</groupId>
        <artifactId>hrn_2.12</artifactId>
    </dependency>
    <dependency>
        <groupId>com.here.traffic.realtime</groupId>
        <artifactId>traffic_v2_java</artifactId>
    </dependency>

</dependencies>

特定の場所のリアルタイム条件を取得します

このチュートリアルでは 、道路セグメントで説明さ れている特定の場所にある HERE Traffic フローカタログからリアルタイムの交通データを取得する方法について説明します。この場合、はBrandenburg Gateを参照してください。

このチュートリアルへの入力は 、ズーム レベル12のタイル ID23618402 です。この Brandenburg GatesegmentID では、Unter der Linden通りの202981252, 203203107 82419435一部を囲むように、Brandenburg GateおよびPariser Platz正方形の近くをカバーしています。

ブランデンブルグ門やパリサー広場に近い道路セグメントに位置しています
図 1. ブランデンブルグ門やパリサー広場に近い道路セグメントに位置しています

以下のコード スニペットでは、次のことが行われます。

ステップ 1 :

データ クライアント ライブラリgetVolatilePartitions()メソッドを使用して、ズーム レベル12で取得したタイル ID のPartitionメタデータを取得します。

ステップ 2 :

データ クライアント ライブラリgetDataAsBytes()メソッドを使用して、Brandenburg Gateタイルで特定のズーム レベル12 ID のパーティションをダウンロードします。

ステップ 3 :

ステップ 2 でダウンロードしたパーティションを使用 traffic_v2 して、 Protobuf スキーマでデータを解析します。

ステップ 4 :

トポロジセグメント ID に関する情報を含む速度項目リストを取得し、特定のセグメント ID で結果をフィルタリングすることで、トラフィックに関する情報を含むすべてのセグメントを取得します。202981252, 203203107 82419435

Scala
Java

/*
 * Copyright (c) 2018-2023 HERE Europe B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import akka.NotUsed
import akka.actor.{ActorSystem, CoordinatedShutdown}
import akka.stream.ActorMaterializer
import akka.stream.javadsl.{Sink, Source}
import com.here.hrn.HRN
import com.here.platform.data.client.common.VolatilePartitionsFilter.byIds
import com.here.platform.data.client.engine.javadsl.{DataEngine, ReadEngine}
import com.here.platform.data.client.javadsl.{DataClient, Partition, QueryApi}
import com.here.platform.data.client.model.AdditionalFields
import com.here.traffic.realtime.v2.Traffic.TrafficItems

import scala.collection.convert.ImplicitConversions.`collection AsScalaIterable`
import scala.concurrent.ExecutionContext.Implicits.global

object RealTimeTrafficTutorialScala {

  private val FLOW_CATALOG = HRN.fromString("hrn:here:data::olp-here:here-traffic-flow-v2")
  private val FLOW_LAYER = "realtime-traffic-flow-volatile"

  def main(args: Array[String]): Unit = {

    val actorSystem: ActorSystem = ActorSystem.create("flow")
    val actorMaterializer: ActorMaterializer = ActorMaterializer.create(actorSystem)
    val queryApi: QueryApi = DataClient.get(actorSystem).queryApi(FLOW_CATALOG)
    val readEngine: ReadEngine = DataEngine.get(actorSystem).readEngine(FLOW_CATALOG)

    val berlinCityCenterTileId = "23618402"

    val segmentsIdForStreet = List(202981252, 203203107, 82419435)

    // Step 1: Retrieve Partition metadata for the given Brandenburg Gate Tile ID on zoom level 8
    val partition = queryApi
      .getVolatilePartitions(FLOW_LAYER,
                             byIds(Set(berlinCityCenterTileId)),
                             AdditionalFields.AllFields)
      .thenCompose((partitionsSource: Source[Partition, NotUsed]) =>
        partitionsSource.runWith(Sink.head(), actorMaterializer))
      .toCompletableFuture
      .join()

    // Step 2: Download partition for the given `Brandenburg Gate` Tile ID on zoom level `12`
    val partDownloadedTraffic = readEngine.getDataAsBytes(partition).toCompletableFuture.join()

    // Step 3: Parse real-time traffic data
    val speedsTrafficItems = TrafficItems.parseFrom(partDownloadedTraffic)

    // Step 4: Fetch speed item list that contains information about topology segment IDs
    // and then get all segments with information about traffic
    // by filtering results by given segments IDs: `202981252, 203203107 82419435`.
    val realTimeTraffic = speedsTrafficItems.getItemsList
      .filter(item =>
        item.getTopologySegment.getTopologySegmentIdList.exists(segmentsIdForStreet.contains))
      .flatMap(traffic => traffic.getFlow.getSegmentList)

    printf(
      s"The real-time traffic data for the given segments Ids [${segmentsIdForStreet.map(_.longValue()).mkString(", ")}] is: $realTimeTraffic")

    CoordinatedShutdown
      .get(actorSystem)
      .run(CoordinatedShutdown.unknownReason)
      .onComplete(print)

  }

}



/*
 * Copyright (c) 2018-2023 HERE Europe B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import akka.actor.ActorSystem;
import akka.actor.CoordinatedShutdown;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Sink;
import com.google.protobuf.InvalidProtocolBufferException;
import com.here.hrn.HRN;
import com.here.platform.data.client.common.VolatilePartitionsFilter;
import com.here.platform.data.client.engine.javadsl.DataEngine;
import com.here.platform.data.client.engine.javadsl.ReadEngine;
import com.here.platform.data.client.javadsl.DataClient;
import com.here.platform.data.client.javadsl.Partition;
import com.here.platform.data.client.javadsl.QueryApi;
import com.here.traffic.realtime.v2.*;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

public class RealTimeTrafficTutorial {

  private static final HRN FLOW_CATALOG =
      HRN.fromString("hrn:here:data::olp-here:here-traffic-flow-v2");
  private static final String FLOW_LAYER = "realtime-traffic-flow-volatile";

  public static void main(String[] args)
      throws ExecutionException, InterruptedException, InvalidProtocolBufferException {
    ActorSystem actorSystem = ActorSystem.create("flow");
    ActorMaterializer actorMaterializer = ActorMaterializer.create(actorSystem);
    QueryApi queryApi = DataClient.get(actorSystem).queryApi(FLOW_CATALOG);
    ReadEngine readEngine = DataEngine.get(actorSystem).readEngine(FLOW_CATALOG);

    String berlinCityCenterTileId = "23618402";

    List<Integer> segmentsIdForStreet =
        new ArrayList<>(Arrays.asList(202981252, 203203107, 82419435));

    // Step 1: Retrieve Partition metadata for the given Brandenburg Gate Tile ID on zoom level 8
    Partition partition =
        queryApi
            .getVolatilePartitions(
                FLOW_LAYER,
                new VolatilePartitionsFilter.Builder()
                    .withIds(Collections.singleton(berlinCityCenterTileId))
                    .build(),
                Collections.emptySet())
            .thenCompose(
                partitionsSource -> partitionsSource.runWith(Sink.head(), actorMaterializer))
            .toCompletableFuture()
            .join();

    // Step 2: Download partition for the given `Brandenburg Gate` Tile ID on zoom level `12`
    byte[] partDownloadedTraffic = readEngine.getDataAsBytes(partition).toCompletableFuture().get();

    // Step 3: Parse real-time traffic data
    Traffic.TrafficItems speedsTrafficItems = Traffic.TrafficItems.parseFrom(partDownloadedTraffic);

    // Step 4: Fetch speed item list that contains information about topology segment IDs
    // and then get all segments with information about traffic
    // by filtering results by given segments IDs: `202981252, 203203107 82419435`.
    List<FlowOuterClass.Segment> realTimeTraffic =
        speedsTrafficItems
            .getItemsList()
            .stream()
            .filter(
                item ->
                    !Collections.disjoint(
                        item.getTopologySegment().getTopologySegmentIdList(), segmentsIdForStreet))
            .flatMap(t -> t.getFlow().getSegmentList().stream())
            .collect(Collectors.toList());

    System.out.printf(
        "The real-time traffic data for the given segments Ids %s is: %s",
        segmentsIdForStreet, realTimeTraffic);

    CoordinatedShutdown.get(actorSystem)
        .run(CoordinatedShutdown.unknownReason(), Optional.empty())
        .toCompletableFuture()
        .join();
  }
}

アプリケーションを実行するには、次のコマンドを実行します。

Scala
Java

mvn compile exec:java -D"exec.mainClass"="RealTimeTrafficTutorialScala"


mvn compile exec:java -D"exec.mainClass"="RealTimeTrafficTutorial"

プログラムの結果によれば、1.5304710.0交通渋滞が発生する可能性がありません。202981252セグメントおよび82419435セグメントの平均速度は、10.0 kphセグメントの平均速度2032031078.35 kphです。 交通渋滞や道路閉鎖などの障害物がない場合に、車両がセグメントを通過できる速度は 10.0 、で示さ free_flow_speed_kphれているように、すべてのセグメントに適用されます。 交通量の平均速度ですが、制限速度に制限 されているのは、10.020298125282419435セグメントおよび8.3582419435セグメントです(average_speed_capped_kphを参照)。

The real-time traffic data for the given segments Ids [202981252, 203203107, 82419435] is: 
[
speed {
  average_speed_kph: 10.0
  average_speed_capped_kph: 10.0
  free_flow_speed_kph: 10.0
}
, speed {
  average_speed_kph: 8.35
  average_speed_capped_kph: 8.35
  free_flow_speed_kph: 10.0
}
jam_factor: 1.53047
, speed {
  average_speed_kph: 10.0
  average_speed_capped_kph: 10.0
  free_flow_speed_kph: 10.0
}
]

結論

このチュートリアルで は、 HERE Traffic フロー カタログについて学習し、このカタログを使用して交通状況データについての情報を取得する方法を学習しました。

詳細情報

このチュートリアルで扱うトピックの詳細については、次のソースを参照してください。

」に一致する結果は 件です

    」に一致する結果はありません