その他の交通機能

HERE SDKの高度な交通機能を使用して、リアルタイム交通情報データでマップアプリケーションを強化します。ライブの交通流とインシデントを地図に表示して、ユーザーに情報を提供し、効率的にナビゲートできるようにします。また、特定の交通事案を選択して強調表示し、詳細ビューを表示できます。

Navigateの場合、ラジオ基地局からの交通情報を組み込むこともできます。

リアルタイムの交通流とインシデントを地図に表示する

マップレイヤーの状態trafficIncidentsを有効にすることで、交通事案を地図上で簡単に視覚化できます。HERE SDK は、現在の交通状況を確認するための別のレイヤーもサポートしています。地図上でレイヤーを表示または非表示にする方法については、以下の例を参照してください。

スクリーンショット:地図上で視覚化された交通事案。

レイヤーを設定すると、地図の表示エリアが自動的に更新されます。そのため、地図をあらゆる方向に自由にパンして、最新の交通事案を確認できます。

多くの状況で、ドライバーは市内または市外の現在の交通渋滞に基づいて最速ルートを見つけることに関心を持っています。HERE SDK を使用すると、現在のすべての交通渋滞を保持するレイヤーを表示できます。交通渋滞は混雑の度合いを示すさまざまな色のラインで視覚化され、常にリアルタイムで更新されます。この機能にはオンライン接続が必要で、通常よりも若干多くのデータを消費します。ただし、交通ラインはマップ タイルの一部として表示されるため、パフォーマンスが高くなります。

一緒に、または単独で、わずか数行のコードでこのような交通情報を地図上に視覚化できます。

func enableTrafficVisualization() {    
    do {
        // Set the traffic flow refresh period to 5 * 60 seconds (5 minutes).
        // If MapFeatures.trafficFlow is disabled, no requests are made.
        //
        // Note: This code initiates periodic calls to the HERE Traffic backend. Depending on your contract,
        // each call may be charged separately. It is the application's responsibility to decide how
        // often this code should be executed.
        try MapContentSettings.setTrafficRefreshPeriod(5 * 60.0)
    } catch let error as MapContentSettings.TrafficRefreshPeriodError {
        print("TrafficRefreshPeriodError: \(error)")
    } catch {
        print("An unexpected error occurred: \(error)")
    }

    // Once these layers are added to the map, they will be automatically updated while panning the map.
    mapView.mapScene.enableFeatures([MapFeatures.trafficFlow : MapFeatureModes.trafficFlowWithFreeFlow])
    // MapFeatures.trafficIncidents renders traffic icons and lines to indicate the location of incidents.
    mapView.mapScene.enableFeatures([MapFeatures.trafficIncidents: MapFeatureModes.defaultMode])
}

必要に応じて、MapFeatures.trafficFlowとMapFeatures.trafficIncidentsについて、バックエンドから最新のトラフィックデータを取得するためにリクエストを実行する頻度を指定することもできます。マップビューが静的な状態に保たれるシナリオでは、この設定をMapContentSettings.setTrafficRefreshPeriod(5 * 60.0)で行うのが最も有効です。

交通状況の更新期間の設定に関係なく、ビューポートが変更された場合、HERE SDKは更新されたビューポートを正しくレンダリングするために新しい交通状況データを取得する必要があります。

注

これらの機能が有効になっている場合、ターン・バイ・ターンナビ中はビューポートの変更が1秒間に複数回発生する可能性があり、トラフィックベクタータイルのリクエストが大量に発生する可能性があります。代替策として、TrafficOnRouteを使用して、ルート沿いの交通情報の表示のみを更新することを検討してください。

トラフィックレイヤーを無効にするには、以下を呼び出します。

mapView.mapScene.disableFeatures([MapFeatures.trafficFlow, MapFeatures.trafficIncidents])

交通流ラインは次のように色分けされています。

  • 緑:交通量が通常
  • 黄:交通量が多い
  • 赤:交通量が非常に多い
  • 黒:交通が遮断されている
スクリーンショット:インシデントとともに地図上に視覚化されている交通流。

交通障害を選択する

trafficIncidents が MapView に表示されている場合、タップ ハンドラーを設定し、交通事案を選択して詳細情報を取得できます。

// Conforming to TapDelegate protocol.
func onTap(origin: Point2D) {
    // Can be nil when the map was tilted and the sky was tapped.
    if let touchGeoCoords = mapView.viewToGeoCoordinates(viewCoordinates: origin) {
        tappedGeoCoordinates = touchGeoCoords

        // Pick incidents that are shown in trafficIncidents.
        pickTrafficIncident(touchPointInPixels: origin)
    }
}

// Traffic incidents can only be picked, when trafficIncidents is visible.
func pickTrafficIncident(touchPointInPixels: Point2D) {
    let originInPixels = Point2D(x: touchPointInPixels.x, y: touchPointInPixels.y)
    let sizeInPixels = Size2D(width: 1, height: 1)
    let rectangle = Rectangle2D(origin: originInPixels, size: sizeInPixels)

    mapView.pickMapContent(inside: rectangle, completion: onPickMapContent)
}

// MapViewBase.PickMapContentHandler to receive picked map content.
func onPickMapContent(mapContentResult: PickMapContentResult?) {
    if mapContentResult == nil {
        // An error occurred while performing the pick operation.
        return
    }

    let trafficIncidents = mapContentResult!.trafficIncidents
    if trafficIncidents.count == 0 {
        print("No traffic incident found at picked location")
    } else {
        print("Picked at least one incident.")
        let firstIncident = trafficIncidents.first!
        showDialog(title: "Traffic incident picked:", message: "Type: \(firstIncident.type.rawValue)")

        // Find more details by looking up the ID via TrafficEngine.
        findIncidentByID(firstIncident.originalId)
    }

    // Optionally, look for more map content like embedded POIs.
}

タップ ハンドラーを使用すると、ビュー座標内のタッチされた位置を取得し、それを mapView.pickMapContent() に渡すことができます。ここではポイントサイズの長方形を使用しているだけですが、選択エリアを拡大して、より多くのコンテンツを一度に含めることもできます。

コールバックは、TrafficIncidentResult を含めることができる PickMapContentResult を提供しますが、デフォルトの POI マーカーなど、地図上に常に表示される他の埋め込みタイプも含めることができます。TrafficIncidentResultタイプはすでにインシデントに関するほとんどの情報を提供していますが、利用可能な情報をすべて取得するには、TrafficEngine (以下も参照) を使用して、選択したインシデントをIDで検索します。

func findIncidentByID(_ originalId: String) {
    let trafficIncidentsLookupOptions = TrafficIncidentLookupOptions()
    // Optionally, specify a language:
    // the language of the country where the incident occurs is used.
    // trafficIncidentsLookupOptions.languageCode = LanguageCode.EN_US
    trafficEngine.lookupIncident(with: originalId,
                                 lookupOptions: trafficIncidentsLookupOptions,
                                 completion: onTrafficIncidentCompletion)
}

// TrafficIncidentCompletionHandler to receive traffic incidents from ID.
func onTrafficIncidentCompletion(trafficQueryError: TrafficQueryError?, trafficIncident: TrafficIncident?) {
    if trafficQueryError == nil {
        print("Fetched TrafficIncident from lookup request." +
                " Description: " + trafficIncident!.description.text)
    } else {
        showDialog(title: "TrafficLookupError:", message: trafficQueryError.debugDescription)
    }
}

使用例は、GitHubから「Traffic」サンプルアプリの一部として入手できます。

ラジオ基地局から交通放送を受信する (Navigateでのみ使用可能)

TrafficDataProviderインターフェースを使用すると、HERE SDKで交通ブロードキャストを提供するラジオ基地局信号を統合できます。

TrafficBroadcastはRDS-TMC形式の交通データを想定しており、インターネット接続なしで使用できます。このような場合、OfflineRoutingEngineレイヤーがrdsTrafficを使用して有効化されていれば、LayerConfigurationはラジオチャネル経由で受信した交通データを利用できます。LayerConfigurationの使用方法の詳細については、こちらを参照してください。

trafficBroadcast.activate()メソッドを呼び出して、交通データイベントを受信する必要があります。

TrafficBroadcast は、位置情報ソースから提供される新しい位置に絶え間なく反応し、LocationListener として機能します。activate()の呼び出しに関係なく、位置を更新する必要があります。

注 (Navigateにのみ適用)

このインターフェースを採用するには特別なハードウェアが必要です。詳細については、HERE 担当者にお問い合わせください。これはベータ機能としてリリースされていることに注意してください。

ルート上の交通状況を更新および視覚化する

最新の交通状況に基づいてルートを最新の状態に保ち、地図上で視覚化します。このセクションでは、既存のルートの交通データを更新する方法、更新されたETAを抽出する方法、ルート沿いの交通状況を視覚化する方法、交通状況が変化した際により適した代替ルートを見つけるために、ナビゲーション中に動的ルート検索を活用する方法について説明します。

ルートの交通情報を更新する

ご自身のシナリオに最も合うオプションを使用してください。

calculateTrafficOnRoute()とrefreshRoute()によってルートの距離とジオメトリーが変更されることはありません。

注(Navigateにのみ適用)

または、DynamicRoutingEngineを使用してナビゲーション中によりよいルートを検索することもできます。これらのルートは現在の交通流に基づいて最適化されます。その結果、交通量の多い道路を迂回するための新しいルートジオメトリーも含まれる場合があります。DynamicRoutingEngineの詳細については、「ナビゲーション」セクションを参照してください。

ルートプレビュー中に交通状況を更新する

routingEngine.calculateTrafficOnRoute(..)メソッドは、作成後に特定のセクションまたはルート全体の交通状況を更新します。ナビゲーション中またはルートプレビューコンテキストでこれを計算できます。

インデックスと最後にアクセスした位置からのオフセット(メートル単位)を使用して、最後に移動したルートセクションからの交通状況を再計算することで、これを行います。ルートプレビューコンテキストでは、ルート全体の交通情報を更新するために、lastTraveledSectionIndexとtraveledDistanceOnLastSectionInMetersを0に設定できます。

このメソッドは、主にルートプレビュー用に設計された画面で次のように利用できます。

func updateTrafficOnRoute(route: Route?) {
    // Since traffic is being calculated for the entire route, lastTraveledSectionIndex and traveledDistanceOnLastSectionInMeters are set to 0.
    let lastTraveledSectionIndex = 0
    let traveledDistanceOnLastSectionInMeters = 0

    // Note: calculateTrafficOnRoute requires a route with routeHandle.
    // Enable it by setting routeOptions.enableRouteHandle to true when creating the route.
    routingEngine.calculateTrafficOnRoute(
        route: route!,
        lastTraveledSectionIndex: Int32(lastTraveledSectionIndex),
        traveledDistanceOnLastSectionInMeters: Int32(traveledDistanceOnLastSectionInMeters)
    ) { routingError, trafficOnRoute in
        if let error = routingError {
            print("CalculateTrafficOnRoute error: \(error)")
        } else if let trafficOnRoute = trafficOnRoute {
            self.showUpdatedETA(trafficOnRoute: trafficOnRoute)
        }
    }
}

TrafficOnRouteからの最新のETAはTrafficOnSpanから確認できます。各TrafficOnSpanはルート沿いの交通情報を提供します。次のメソッドを使用して更新されたETAを抽出できます。

private func showUpdatedETA(trafficOnRoute: TrafficOnRoute) {
    for section in trafficOnRoute.trafficSections {
        var updatedETAInSeconds = 0.0;
        section.trafficSpans.forEach{ updatedETAInSeconds = updatedETAInSeconds + Double($0.duration)}
        var updatedTrafficDelayInSeconds = 0.0;
        section.trafficSpans.forEach{ updatedTrafficDelayInSeconds = updatedTrafficDelayInSeconds + Double($0.trafficDelay)}
        let updatedETAString = String(format: "Updated travel duration %@\nUpdated traffic delay %@",
                                      timeUtils.formatTime(sec: updatedETAInSeconds),
                                      timeUtils.formatTime(sec: updatedTrafficDelayInSeconds))
        showDialog(title: "Updated traffic", message: updatedETAString)
    }
}

注

交通状況の更新では、予測モデルを使用してルートに沿った状況を予測しますが、マップレイヤーに表示されるリアルタイムの交通状況とは異なる場合があります。これらの違いの詳細については、「トラフィック」を参照してください。

ターンバイターンナビの実行中に交通状況を更新する(Navigateでのみ使用可能)

定期的なcalculateTrafficOnRoute()の例を含め、visualNavigator.trafficOnRouteによるガイダンス固有の交通状況の更新については、「ナビゲーション中のETAおよび交通情報を更新する」を参照してください。

ルート上の交通状況を視覚化する

HERE SDKは、ルートポリライン上に交通状況を直接視覚化できます。リアルタイムの交通流レイヤーに隣接して地図上にルートをレンダリングする方法と、route自体から取得した予測交通データを使用してカスタムの交通情報オーバーレイを描画する2つ方法から選択できます。

リアルタイム交通データと予測交通データのデータソースの違いと各方法の使い分けを理解するには、「トラフィック」を参照してください。

交通流に隣接するポリラインをレンダリングする

デフォルトで HERE SDK は交通流レイヤーをカラー エンコーディングして交通状況を示します。MapMeasureDependentRenderSizeを使用すると、MapMeasure.Kindに応じてレンダリングするポリラインの幅が決定され、交通ポリラインに隣接するようにレンダリングします。

スクリーンショット:交通流に隣接するポリライン。

これを実装する例は次のとおりです。

// Show route as polyline.
let routeGeoPolyline = route.geometry
let polylineColor = UIColor(red: 0.051, green: 0.380, blue: 0.871, alpha: 1)
let outlineColor = UIColor(red: 0.043, green: 0.325, blue: 0.749, alpha: 1)
do {
    // Below, we're creating an instance of MapMeasureDependentRenderSize. This instance will use the scaled width values to render the route polyline.
    // We can also apply the same values to MapArrow.setMeasureDependentTailWidth().
    // The parameters for the constructor are: the kind of MapMeasure (in this case, ZOOM_LEVEL), the unit of measurement for the render size (PIXELS), and the scaled width values.
    let mapMeasureDependentLineWidth = try MapMeasureDependentRenderSize(measureKind: MapMeasure.Kind.zoomLevel, sizeUnit: RenderSize.Unit.pixels, sizes: getDefaultLineWidthValues())

    // We can also use MapMeasureDependentRenderSize to specify the outline width of the polyline.
    let outlineWidthInPixel = 1.23 * mapView.pixelScale
    let mapMeasureDependentOutlineWidth = try MapMeasureDependentRenderSize(sizeUnit: RenderSize.Unit.pixels, size: outlineWidthInPixel)
    let routeMapPolyline = try MapPolyline(geometry: routeGeoPolyline,
                                            representation: MapPolyline.SolidRepresentation(
                                                lineWidth: mapMeasureDependentLineWidth,
                                                color: polylineColor,
                                                outlineWidth: mapMeasureDependentOutlineWidth,
                                                outlineColor: outlineColor,
                                                capShape: LineCap.round))

    mapView.mapScene.addMapPolyline(routeMapPolyline)
    mapPolylineList.append(routeMapPolyline)
} catch let error {
    fatalError("Failed to render MapPolyline. Cause: \(error)")
}

MapMeasureDependentRenderSizeに指定された幅の値は、2つの連続する各データポイントの間に直線で補間されます。次のように生成できます。

// Returns a dictionary where the key is the zoom level and the value is the corresponding scaled width.
private func getDefaultLineWidthValues() -> [Double:Double] {
    var widthsPerZoomLevel : [Double:Double] = [:]
    let pixelScale = mapView.pixelScale
    // Here width value will remain 2.18 from 0.0 zoom level to 6.0.
    // From 6.0 the updated value 2.48 will be used.
    widthsPerZoomLevel[0.0] = 2.18 * pixelScale
    widthsPerZoomLevel[6.0] = 2.48 * pixelScale
    widthsPerZoomLevel[7.0] = 2.78 * pixelScale
    widthsPerZoomLevel[11.0] = 3.1 * pixelScale
    widthsPerZoomLevel[16.0] = 3.15 * pixelScale
    widthsPerZoomLevel[17.0] = 3.35 * pixelScale
    widthsPerZoomLevel[18.0] = 3.78 * pixelScale
    widthsPerZoomLevel[19.0] = 6.5 * pixelScale
    widthsPerZoomLevel[20.0] = 10.2 * pixelScale
    widthsPerZoomLevel[24.0] = 77.5 * pixelScale
    return widthsPerZoomLevel
}

VisualNavigatorを使用してポリラインをレンダリングする(Navigateのみ)

経路誘導ガイダンス中は、VisualNavigatorのデフォルト値を使用します。これらの値はdefaultRouteManeuverArrowMeasureDependentWidthsを使用して取得します。幅の値をさらにスケーリングすると、さまざまなデバイス間ですっきりと一貫した表示が可能になります。

// Retrieves the default widths of a route polyline and maneuver arrows from VisualNavigator,
// scaling them based on the screen's pixel density.
private func getDefaultLineWidthValues() -> [Double:Double] {
    var widthsPerZoomLevel: [Double: Double] = [:];
    for defaultValues in VisualNavigator.defaultRouteManeuverArrowMeasureDependentWidths() {
            let key = defaultValues.key.value
            let value = defaultValues.value * mapView.pixelScale
            widthsPerZoomLevel[key] = value
        }
    return widthsPerZoomLevel
}

ルートに沿ってカスタムトラフィックをレンダリングする

交通流に隣接してルートのポリラインをレンダリングする代わりに、Routeオブジェクトの一部として利用可能な交通データを使用して、自身で交通状況をレンダリングすることもできます。これは、実際のガイダンスを開始する前のルートプレビューのユースケースに適しています。

このアプローチの場合、交通情報には交通流スキームによって提供されるリアルタイム情報ではなく、ルートからの予測データが含まれるため、精度が低くなる可能性があります。ただし、交通流レイヤーに使用されるカラーエンコーディングと同様に、0 (交通量なし) から10 (道路が通行止め) までの範囲を持つdynamicSpeedInfo.calculateJamFactor()を使用して、ルート上の交通量を示すことができます。各RouteのSectionには、さまざまなDynamicSpeedInfoインスタンスを含めることができます。これらは、Spanに沿って次のSpanまで有効です。各Spanジオメトリーは、ルート全体のポリライン形状の一部であるポリラインで表されます。

次のコード スニペットは、Section の最初の Span の DynamicSpeedInfo 要素を取得する方法を示しています。

let firstSection = route.sections[0]
let dynamicSpeed = firstSection.spans[0].dynamicSpeedInfo

DynamicSpeedInfo には、予想されるデフォルトの移動速度である baseSpeedInMetersPerSecond が含まれています。これは、道路の現在の制限速度と同じではない場合があることに注意してください。道路状況が悪い場合は、より遅い移動速度が妥当である場合があります。さらに、trafficSpeedInMetersPerSecondを使用すると、現在の交通状況に基づいて推定される実際の移動速度を取得できます。

この値を適切な色にマッピングする方法の例を以下に示します。

図:渋滞要素。

通常、渋滞要素は次のように解釈します。

  • 0 <=渋滞要素< 4:交通量がないか少ない。
  • 4 <=渋滞要素< 8:交通量が中程度、または交通の流れが遅い。
  • 8 <=渋滞要素< 10:激しい渋滞。
  • 渋滞要素= 10:道路が封鎖されており、通行不可。

注

DynamicSpeedInfoから取得できる渋滞要素は、trafficSpeedInMetersPerSecond / baseSpeedInMetersPerSecondの比率から区分線形的に算出されており、道路タイプやその他のパラメーターは考慮されていない点に注意してください。そのため、提供される渋滞要素は、マップビュー上の交通流の視覚要素 (有効な場合) と正確に一致するとは限りません。さらに、RoutingEngineは予測型位置情報サービスを使用して、ルート上を走行しながら今後の交通状況を予測します。一方、交通流の視覚要素は現時点 (リアルタイム) の情報のみを表示します。事前にレンダリングされた交通流では、現在のズームレベルに基づいて異なる色表現が使用される可能性があることにも注意してください。

指定された到着予測時刻に一致するルートに沿った予測交通量を優先するか、代わりにリアルタイムの交通状況を表示するかはアプリで決定されます。この場合、将来目的地に到着した時点で正確ではなくなる可能性があります。

後者の場合に推奨されるアプローチは、ルート自体に交通状況を追加でレンダリングするのではなく、ルートのポリラインに地図メジャー依存の幅を使用して、ルートと交通流を並べて表示することです。

スクリーンショット:渋滞要素を使用してルート上に交通状況が視覚化されている。

ルートに沿って交通状況を視覚化する場合は、複数の色のMapPolylineオブジェクトをセクションの各スパンにレンダリングすることを検討してください。

// This renders the traffic jam factor on top of the route as multiple MapPolylines per span.
private func showTrafficOnRoute(_ route: Route) {
    if route.lengthInMeters / 1000 > 5000 {
        print("Skip showing traffic-on-route for longer routes.")
        return
    }

    for section in route.sections {
        for span in section.spans {
            let dynamicSpeedInfo: DynamicSpeedInfo? = span.dynamicSpeedInfo
            guard let lineColor = getTrafficColor(dynamicSpeedInfo?.calculateJamFactor()) else {
                // Skip rendering low traffic.
                continue
            }

            let widthInPixels = 10.0
            do {
                let trafficSpanMapPolyline = try MapPolyline(geometry: span.geometry,
                                                  representation: MapPolyline.SolidRepresentation(
                                                    lineWidth: try MapMeasureDependentRenderSize(
                                                        sizeUnit: RenderSize.Unit.pixels,
                                                        size: widthInPixels),
                                                    color: lineColor,
                                                    capShape: LineCap.round))

                mapView.mapScene.addMapPolyline(trafficSpanMapPolyline)
                mapPolylineList.append(trafficSpanMapPolyline)
            } catch let error {
                fatalError("Failed to render MapPolyline. Cause: \(error)")
            }
        }
    }
}

// Define a traffic color scheme based on the route's jam factor.
// 0 <= jamFactor < 4: No or light traffic.
// 4 <= jamFactor < 8: Moderate or slow traffic.
// 8 <= jamFactor < 10: Severe traffic.
// jamFactor = 10: No traffic, that is the road is blocked.
// Returns nil in case of no or light traffic.
private func getTrafficColor(_ jamFactor: Double?) -> UIColor? {
    guard let jamFactor = jamFactor else {
        return nil
    }
    if jamFactor < 4 {
        return nil
    } else if jamFactor >= 4 && jamFactor < 8 {
        return UIColor(red: 1, green: 1, blue: 0, alpha: 0.63) // Yellow
    } else if jamFactor >= 8 && jamFactor < 10 {
        return UIColor(red: 1, green: 0, blue: 0, alpha: 0.63) // Red
    }
    return UIColor(red: 0, green: 0, blue: 0, alpha: 0.63) // Black
}

この例では、交通状況がある各スパンが個別のポリラインとしてレンダリングされているため、パフォーマンス上の理由から、長いルートの交通状況レンダリングがスキップされることに注意してください。


このページは役に立ちましたか?