その他の交通機能

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

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

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

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

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

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

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

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

private void enableTrafficVisualization() {
    // Try to refresh the TRAFFIC_FLOW vector tiles 5 minutes.
    // If MapFeatures.TRAFFIC_FLOW is disabled, no requests are made.
    try {
        MapContentSettings.setTrafficRefreshPeriod(Duration.ofMinutes(5));
    } catch (MapContentSettings.TrafficRefreshPeriodException e) {
        throw new RuntimeException("TrafficRefreshPeriodException: " + e.error.name());
    }

    Map<String, String> mapFeatures = new HashMap<>();
    // Once these traffic layers are added to the map, they will be automatically updated while panning the map.
    mapFeatures.put(MapFeatures.TRAFFIC_FLOW, MapFeatureModes.TRAFFIC_FLOW_WITH_FREE_FLOW);
    // MapFeatures.TRAFFIC_INCIDENTS renders traffic icons and lines to indicate the location of incidents.
    mapFeatures.put(MapFeatures.TRAFFIC_INCIDENTS, MapFeatureModes.DEFAULT);
    mapView.getMapScene().enableFeatures(mapFeatures);
}
private fun enableTrafficVisualization() {
    // Try to refresh the TRAFFIC_FLOW vector tiles 5 minutes.
    // If MapFeatures.TRAFFIC_FLOW 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(Duration.ofMinutes(5))
    } catch (e: TrafficRefreshPeriodException) {
        throw RuntimeException("TrafficRefreshPeriodException: " + e.error.name)
    }

    val mapFeatures: MutableMap<String, String> = HashMap()
    // Once these traffic layers are added to the map, they will be automatically updated while panning the map.
    mapFeatures[MapFeatures.TRAFFIC_FLOW] = MapFeatureModes.TRAFFIC_FLOW_WITH_FREE_FLOW
    // MapFeatures.TRAFFIC_INCIDENTS renders traffic icons and lines to indicate the location of incidents.
    mapFeatures[MapFeatures.TRAFFIC_INCIDENTS] = MapFeatureModes.DEFAULT
    mapView.mapScene.enableFeatures(mapFeatures)
}

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

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

注

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

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

private void disableTrafficVisualization() {
    List<String> mapFeatures = new ArrayList<>();
    mapFeatures.add(MapFeatures.TRAFFIC_FLOW);
    mapFeatures.add(MapFeatures.TRAFFIC_INCIDENTS);
    mapView.getMapScene().disableFeatures(mapFeatures);
}
private fun disableTrafficVisualization() {
    val mapFeatures: MutableList<String> = ArrayList()
    mapFeatures.add(MapFeatures.TRAFFIC_FLOW)
    mapFeatures.add(MapFeatures.TRAFFIC_INCIDENTS)
    mapView.mapScene.disableFeatures(mapFeatures)
}

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

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

交通障害を選択する

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

private void setTapGestureHandler() {
    mapView.getGestures().setTapListener(touchPoint -> {
        GeoCoordinates touchGeoCoords = mapView.viewToGeoCoordinates(touchPoint);
        // Can be null when the map was tilted and the sky was tapped.
        if (touchGeoCoords != null) {
            // Pick incidents that are shown in TRAFFIC_INCIDENTS.
            pickTrafficIncident(touchPoint);
        }
    });
}

// Traffic incidents can only be picked, when TRAFFIC_INCIDENTS is visible.
private void pickTrafficIncident(Point2D touchPointInPixels) {
    Point2D originInPixels = new Point2D(touchPointInPixels.x, touchPointInPixels.y);
    Size2D sizeInPixels = new Size2D(1, 1);
    Rectangle2D rectangle = new Rectangle2D(originInPixels, sizeInPixels);

    // Creates a list of map content type from which the results will be picked.
    // The content type values can be MAP_CONTENT, MAP_ITEMS and CUSTOM_LAYER_DATA.
    ArrayList<MapScene.MapPickFilter.ContentType> contentTypesToPickFrom = new ArrayList<>();

    // MAP_CONTENT is used when picking embedded Carto POIs, traffic incidents, vehicle restriction etc.
    // MAP_ITEMS is used when picking map items such as MapMarker, MapPolyline, MapPolygon etc.
    // Currently we need traffic incidents so adding the MAP_CONTENT filter.
    contentTypesToPickFrom.add(MapScene.MapPickFilter.ContentType.MAP_CONTENT);
    MapScene.MapPickFilter filter = new MapScene.MapPickFilter(contentTypesToPickFrom);

    // If you do not want to specify any filter you can pass filter as NULL and all of the pickable contents will be picked.
    mapView.pick(filter, rectangle, new MapViewBase.MapPickCallback() {
        @Override
        public void onPickMap(@Nullable MapPickResult mapPickResult) {
            if (mapPickResult == null) {
                // An error occurred while performing the pick operation.
                return;
            }

            List<PickMapContentResult.TrafficIncidentResult> trafficIncidents =
                    mapPickResult.getMapContent().getTrafficIncidents();
            if (trafficIncidents.isEmpty()) {
                Log.d(TAG, "No traffic incident found at picked location");
            } else {
                Log.d(TAG, "Picked at least one incident.");
                PickMapContentResult.TrafficIncidentResult firstIncident = trafficIncidents.get(0);
                showDialog("Traffic incident picked:", "Type: " +
                        firstIncident.getType().name());

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

            // Optionally, look for more map content like embedded POIs.
        }
    });
}
private fun setTapGestureHandler() {
    mapView.gestures.tapListener =
        TapListener { touchPoint: Point2D ->
            val touchGeoCoords = mapView.viewToGeoCoordinates(touchPoint)
            // Can be null when the map was tilted and the sky was tapped.
            if (touchGeoCoords != null) {
                // Pick incidents that are shown in TRAFFIC_INCIDENTS.
                pickTrafficIncident(touchPoint)
            }
        }
}

// Traffic incidents can only be picked, when TRAFFIC_INCIDENTS is visible.
private fun pickTrafficIncident(touchPointInPixels: Point2D) {
    val originInPixels = Point2D(touchPointInPixels.x, touchPointInPixels.y)
    val sizeInPixels = Size2D(1.0, 1.0)
    val rectangle = Rectangle2D(originInPixels, sizeInPixels)

    // Creates a list of map content type from which the results will be picked.
    // The content type values can be MAP_CONTENT, MAP_ITEMS and CUSTOM_LAYER_DATA.
    val contentTypesToPickFrom = ArrayList<MapPickFilter.ContentType>()

    // MAP_CONTENT is used when picking embedded Carto POIs, traffic incidents, vehicle restriction etc.
    // MAP_ITEMS is used when picking map items such as MapMarker, MapPolyline, MapPolygon etc.
    // Currently we need traffic incidents so adding the MAP_CONTENT filter.
    contentTypesToPickFrom.add(MapPickFilter.ContentType.MAP_CONTENT)
    val filter = MapPickFilter(contentTypesToPickFrom)

    // If you do not want to specify any filter you can pass filter as NULL and all of the pickable contents will be picked.
    mapView.pick(filter, rectangle, MapPickCallback { mapPickResult ->
        if (mapPickResult == null) {
            // An error occurred while performing the pick operation.
            return@MapPickCallback
        }
        val trafficIncidents =
            mapPickResult.mapContent!!.trafficIncidents
        if (trafficIncidents.isEmpty()) {
            Log.d(TAG, "No traffic incident found at picked location")
        } else {
            Log.d(TAG, "Picked at least one incident.")
            val firstIncident = trafficIncidents[0]
            showDialog(
                "Traffic incident picked:", "Type: " +
                        firstIncident.type.name
            )

            // 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で検索します。

private void findIncidentByID(String originalId) {
    TrafficIncidentLookupOptions trafficIncidentsQueryOptions = new TrafficIncidentLookupOptions();
    // Optionally, specify a language:
    // the language of the country where the incident occurs is used.
    // trafficIncidentsQueryOptions.languageCode = LanguageCode.EN_US;
    trafficEngine.lookupIncident(originalId, trafficIncidentsQueryOptions, new TrafficIncidentLookupCallback() {
        @Override
        public void onTrafficIncidentFetched(@Nullable TrafficQueryError trafficQueryError, @Nullable TrafficIncident trafficIncident) {
            if (trafficQueryError == null) {
                Log.d(TAG, "Fetched TrafficIncident from lookup request." +
                        " Description: " + trafficIncident.getDescription().text);
            } else {
                showDialog("TrafficLookupError:", trafficQueryError.toString());
            }
        }
    });
}
private fun findIncidentByID(originalId: String) {
    val trafficIncidentsQueryOptions = TrafficIncidentLookupOptions()
    // Optionally, specify a language:
    // the language of the country where the incident occurs is used.
    // trafficIncidentsQueryOptions.languageCode = LanguageCode.EN_US;
    trafficEngine.lookupIncident(originalId, trafficIncidentsQueryOptions,
        TrafficIncidentLookupCallback { trafficQueryError, trafficIncident ->
            if (trafficQueryError == null) {
                Log.d(
                    TAG, "Fetched TrafficIncident from lookup request." +
                            " Description: " + trafficIncident!!.description.text
                )
            } else {
                showDialog("TrafficLookupError:", trafficQueryError.toString())
            }
        })
}

使用例は、Java版とKotlin版の両方で提供されている「Traffic」サンプルアプリの一部としてGitHubで入手できます。

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

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

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

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

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

注

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

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

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

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

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

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

注(Navigateのみ)

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

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

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

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

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

public void updateTrafficOnRoute(Route route) {
    // Since traffic is being calculated for the entire route, lastTraveledSectionIndex and traveledDistanceOnLastSectionInMeters are set to 0.
    int lastTraveledSectionIndex = 0;
    int traveledDistanceOnLastSectionInMeters = 0;

    routingEngine.calculateTrafficOnRoute(route, lastTraveledSectionIndex, traveledDistanceOnLastSectionInMeters, new CalculateTrafficOnRouteCallback() {
        @Override
        public void onTrafficOnRouteCalculated(@Nullable RoutingError routingError, @Nullable TrafficOnRoute trafficOnRoute) {
            if (routingError != null) {
                Log.d(TAG, "CalculateTrafficOnRoute error: " + routingError.name());
            } else {
                showUpdatedETA(trafficOnRoute);
            }
        }
    });
}
private fun updateTrafficOnRoute(route: Route) {
    // Since traffic is being calculated for the entire route, lastTraveledSectionIndex and traveledDistanceOnLastSectionInMeters are set to 0.
    val lastTraveledSectionIndex = 0
    val traveledDistanceOnLastSectionInMeters = 0

    routingEngine?.calculateTrafficOnRoute(
        route,
        lastTraveledSectionIndex,
        traveledDistanceOnLastSectionInMeters,
        object : CalculateTrafficOnRouteCallback {
            override fun onTrafficOnRouteCalculated(
                routingError: RoutingError?,
                trafficOnRoute: TrafficOnRoute?
            ) {
                if (routingError != null) {
                    Log.d(TAG, "CalculateTrafficOnRoute error: " + routingError.name)
                } else {
                    showUpdatedETA(trafficOnRoute)
                }
            }
        }
    )
}

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

private void showUpdatedETA(TrafficOnRoute trafficOnRoute) {
    for (TrafficOnSection section : trafficOnRoute.trafficSections) {
        List<TrafficOnSpan> spans = section.trafficSpans;

        long updatedETAInSeconds = spans.stream()
                .mapToLong(span -> span.duration.getSeconds())
                .sum();

        long updatedTrafficDelayInSeconds = spans.stream()
                .mapToLong(span -> span.trafficDelay.getSeconds())
                .sum();

        String updatedETAString = String.format("Updated ETA %s\nUpdated traffic delay %s",
                timeUtils.formatTime(updatedETAInSeconds),
                timeUtils.formatTime(updatedTrafficDelayInSeconds));
        showDialog("Updated traffic", updatedETAString);
    }
}
private fun showUpdatedETA(trafficOnRoute: TrafficOnRoute?) {
    for (section in trafficOnRoute?.trafficSections!!) {
        val spans = section.trafficSpans

        val updatedETAInSeconds = spans.sumOf { it.duration.seconds }
        val updatedTrafficDelayInSeconds = spans.sumOf { it.trafficDelay.seconds }

        val updatedETAString = String.format(
            "Updated ETA %s\nUpdated traffic delay %s",
            timeUtils.formatTime(updatedETAInSeconds),
            timeUtils.formatTime(updatedTrafficDelayInSeconds)
        )
        showDialog("Updated traffic", updatedETAString)
    }
}

注

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

ターンバイターンナビの実行中に交通情報を更新する(HERE SDK for Navigateのみ)

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

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

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

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

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

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

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

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

GeoPolyline routeGeoPolyline = route.getGeometry();
double outlineWidthInPixel;
Color polylineColor = Color.valueOf(0.051f, 0.380f, 0.871f, 1.0f);
Color outlineColor = Color.valueOf(0.043f, 0.325f, 0.749f, 1.0f);
MapPolyline routeMapPolyline = null;
try {
    // 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.
    MapMeasureDependentRenderSize mapMeasureDependentLineWidth = new MapMeasureDependentRenderSize(MapMeasure.Kind.ZOOM_LEVEL, RenderSize.Unit.PIXELS, getDefaultLineWidthValues());

    // We can also use MapMeasureDependentRenderSize to specify the outline width of the polyline.
    outlineWidthInPixel = 1.23 * mapView.getPixelScale();
    MapMeasureDependentRenderSize mapMeasureDependentOutlineWidth = new MapMeasureDependentRenderSize(RenderSize.Unit.PIXELS, outlineWidthInPixel);
    routeMapPolyline = new MapPolyline(routeGeoPolyline, new MapPolyline.SolidRepresentation(
            mapMeasureDependentLineWidth,
            polylineColor,
            mapMeasureDependentOutlineWidth,
            outlineColor,
            LineCap.ROUND));

} catch (MapPolyline.Representation.InstantiationException e) {
    Log.e("MapPolyline Representation Exception:", e.error.name());
} catch (MapMeasureDependentRenderSize.InstantiationException e) {
    Log.e("MapMeasureDependentRenderSize Exception:", e.error.name());
}
mapView.getMapScene().addMapPolyline(routeMapPolyline);
val routeGeoPolyline = route.geometry
var outlineWidthInPixel: Double
val polylineColor = Color.valueOf(0.051f, 0.380f, 0.871f, 1.0f)
val outlineColor = Color.valueOf(0.043f, 0.325f, 0.749f, 1.0f)
var routeMapPolyline: MapPolyline? = null
try {
    // 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.
    val mapMeasureDependentLineWidth = MapMeasureDependentRenderSize(
        MapMeasure.Kind.ZOOM_LEVEL, RenderSize.Unit.PIXELS, getDefaultLineWidthValues()
    )

    // We can also use MapMeasureDependentRenderSize to specify the outline width of the polyline.
    outlineWidthInPixel = 1.23 * mapView.pixelScale
    val mapMeasureDependentOutlineWidth = MapMeasureDependentRenderSize(RenderSize.Unit.PIXELS, outlineWidthInPixel)
    routeMapPolyline = MapPolyline(
        routeGeoPolyline, MapPolyline.SolidRepresentation(
            mapMeasureDependentLineWidth,
            polylineColor,
            mapMeasureDependentOutlineWidth,
            outlineColor,
            LineCap.ROUND
        )
    )
} catch (e: MapPolyline.Representation.InstantiationException) {
    Log.e("MapPolyline Representation Exception:", e.error.name)
} catch (e: MapMeasureDependentRenderSize.InstantiationException) {
    Log.e("MapMeasureDependentRenderSize Exception:", e.error.name)
}
mapView.mapScene.addMapPolyline(routeMapPolyline)

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

// Returns a hashMap where the key is the zoom level and the value is the corresponding scaled width.
private HashMap<Double, Double> getDefaultLineWidthValues() {
    HashMap<Double, Double> widthsPerZoomLevel = new HashMap<>();
    // 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.put(0.0, 2.18);
    widthsPerZoomLevel.put(6.0, 2.48);
    widthsPerZoomLevel.put(7.0, 2.78);
    widthsPerZoomLevel.put(11.0, 3.1);
    widthsPerZoomLevel.put(16.0, 3.15);
    widthsPerZoomLevel.put(17.0, 3.35);
    widthsPerZoomLevel.put(18.0, 3.78);
    widthsPerZoomLevel.put(19.0, 6.5);
    widthsPerZoomLevel.put(20.0, 10.2);
    widthsPerZoomLevel.put(24.0, 77.5);
    return scaleCurrentHashMap(widthsPerZoomLevel);
}

private HashMap<Double, Double> scaleCurrentHashMap(HashMap<Double, Double> currentValues) {
    for (Map.Entry<Double, Double> entry : currentValues.entrySet()) {
        entry.setValue(entry.getValue() * mapView.getPixelScale());
    }
    return currentValues;
}
// Returns a hashMap where the key is the zoom level and the value is the corresponding scaled width.
private fun getDefaultLineWidthValues(): HashMap<Double, Double> {
    val widthsPerZoomLevel = HashMap<Double, Double>()
    // 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
    widthsPerZoomLevel[6.0] = 2.48
    widthsPerZoomLevel[7.0] = 2.78
    widthsPerZoomLevel[11.0] = 3.1
    widthsPerZoomLevel[16.0] = 3.15
    widthsPerZoomLevel[17.0] = 3.35
    widthsPerZoomLevel[18.0] = 3.78
    widthsPerZoomLevel[19.0] = 6.5
    widthsPerZoomLevel[20.0] = 10.2
    widthsPerZoomLevel[24.0] = 77.5
    return scaleCurrentHashMap(widthsPerZoomLevel)
}

private fun scaleCurrentHashMap(currentValues: HashMap<Double, Double>): HashMap<Double, Double> {
    for ((_, value) in currentValues) {
        currentValues.put(currentValues.keys.first { currentValues[it] == value }, value * mapView.pixelScale)
    }
    return currentValues
}

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 HashMap<Double, Double> getDefaultLineWidthValues() {
    HashMap<Double, Double> widthsPerZoomLevel = new HashMap<>();
    for (Map.Entry<MapMeasure, Double> defaultValues : VisualNavigator.defaultRouteManeuverArrowMeasureDependentWidths().entrySet()) {
        Double key = defaultValues.getKey().value;
        Double value = defaultValues.getValue() * mapView.getPixelScale();
        widthsPerZoomLevel.put(key, value);
    }
    return widthsPerZoomLevel;
}
// Retrieves the default widths of a route polyline and maneuver arrows from VisualNavigator,
// scaling them based on the screen's pixel density.
private fun getDefaultLineWidthValues(): HashMap<Double, Double> {
    val widthsPerZoomLevel = HashMap<Double, Double>()
    for ((key, value) in VisualNavigator.defaultRouteManeuverArrowMeasureDependentWidths()) {
        widthsPerZoomLevel[key.value] = value * mapView.pixelScale
    }
    return widthsPerZoomLevel
}

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

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

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

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

Section firstSection = route.getSections().get(0);
DynamicSpeedInfo dynamicSpeed = firstSection.getSpans().get(0).getDynamicSpeedInfo();
val firstSection = route.sections[0]
val 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 void showTrafficOnRoute(Route route) {
    if (route.getLengthInMeters() / 1000 > 5000) {
        Log.d(TAG, "Skip showing traffic-on-route for longer routes.");
        return;
    }

    for (Section section : route.getSections()) {
        for (Span span : section.getSpans()) {
            DynamicSpeedInfo dynamicSpeed = span.getDynamicSpeedInfo();
            Color lineColor = getTrafficColor(dynamicSpeed.calculateJamFactor());
            if (lineColor == null) {
                // We skip rendering low traffic.
                continue;
            }
            float widthInPixels = 10;
            MapPolyline trafficSpanMapPolyline = null;
            try {
                trafficSpanMapPolyline = new MapPolyline(span.getGeometry(), new MapPolyline.SolidRepresentation(
                                new MapMeasureDependentRenderSize(RenderSize.Unit.PIXELS, widthInPixels),
                                lineColor,
                                LineCap.ROUND));
            } catch (MapPolyline.Representation.InstantiationException e) {
                Log.e("MapPolyline Representation Exception:", e.error.name());
            } catch (MapMeasureDependentRenderSize.InstantiationException e) {
                Log.e("MapMeasureDependentRenderSize Exception:", e.error.name());
            }

            mapView.getMapScene().addMapPolyline(trafficSpanMapPolyline);
            mapPolylines.add(trafficSpanMapPolyline);
        }
    }
}

// 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 null in case of no or light traffic.
@Nullable
private Color getTrafficColor(Double jamFactor) {
    if (jamFactor == null || jamFactor < 4) {
        return null;
    } else if (jamFactor >= 4 && jamFactor < 8) {
        return Color.valueOf(1, 1, 0, 0.63f); // Yellow
    } else if (jamFactor >= 8 && jamFactor < 10) {
        return Color.valueOf(1, 0, 0, 0.63f); // Red
    }
    return Color.valueOf(0, 0, 0, 0.63f); // Black
}
// This renders the traffic jam factor on top of the route as multiple MapPolylines per span.
private fun showTrafficOnRoute(route: Route) {
    if (route.lengthInMeters / 1000 > 5000) {
        Log.d(TAG, "Skip showing traffic-on-route for longer routes.")
        return
    }

    for (section in route.sections) {
        for (span in section.spans) {
            val dynamicSpeed: DynamicSpeedInfo? = span.dynamicSpeedInfo
            val lineColor = getTrafficColor(dynamicSpeed?.calculateJamFactor())
                ?: // We skip rendering low traffic.
                continue
            val widthInPixels = 10f
            var trafficSpanMapPolyline: MapPolyline? = null
            try {
                trafficSpanMapPolyline = MapPolyline(
                    span.geometry, MapPolyline.SolidRepresentation(
                        MapMeasureDependentRenderSize(
                            RenderSize.Unit.PIXELS,
                            widthInPixels.toDouble()
                        ),
                        lineColor,
                        LineCap.ROUND
                    )
                )
            } catch (e: MapPolyline.Representation.InstantiationException) {
                Log.e("MapPolyline Representation Exception:", e.error.name)
            } catch (e: MapMeasureDependentRenderSize.InstantiationException) {
                Log.e("MapMeasureDependentRenderSize Exception:", e.error.name)
            }

            if (trafficSpanMapPolyline != null) {
                mapView.mapScene.addMapPolyline(trafficSpanMapPolyline)
                mapPolylines.add(trafficSpanMapPolyline)
            }
        }
    }
}

// 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, ie. the road is blocked.
// Returns null in case of no or light traffic.
private fun getTrafficColor(jamFactor: Double?): Color? {
    if (jamFactor == null || jamFactor < 4) {
        return null
    } else if (jamFactor >= 4 && jamFactor < 8) {
        return Color.valueOf(1f, 1f, 0f, 0.63f) // Yellow
    } else if (jamFactor >= 8 && jamFactor < 10) {
        return Color.valueOf(1f, 0f, 0f, 0.63f) // Red
    }
    return Color.valueOf(0f, 0f, 0f, 0.63f) // Black
}

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


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