How to add congestion highlighting to routes generated by Bing Maps

Tom 26 Reputation points
2025-07-30T13:49:34.94+00:00

I'm using the Bing Maps Directions Manager and Traffic Manager and they are setup similar to the example below.

let trafficManager, directionsManager;
let map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
    /* No need to set credentials if already passed in URL */
    center: new Microsoft.Maps.Location(47.606209, -122.332071),
    zoom: 12
});
Microsoft.Maps.loadModule('Microsoft.Maps.Traffic', function () {
    trafficManager = new Microsoft.Maps.Traffic.TrafficManager(map);
    trafficManager.show();
});
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
    directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
    // Set Route Mode to driving
    directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
    var waypoint1 = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond', location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789) });
    var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle', location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797) });
    directionsManager.addWaypoint(waypoint1);
    directionsManager.addWaypoint(waypoint2);
    // Set the element in which the itinerary will be rendered
    directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('printoutPanel') });
    directionsManager.calculateDirections();
});

Bing Maps sometimes adds indicators on routes by changing the route colour based on the traffic conditions. You can see an example of the red section of the route in the screenshot taken from https://www.bing.com/map

enter image description here

Is there a way to add this feature using the directions and traffic managers?

Azure Maps
Azure Maps
An Azure service that provides geospatial APIs to add maps, spatial analytics, and mobility solutions to apps.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. rbrundritt 21,191 Reputation points Microsoft Employee Moderator
    2025-07-30T19:01:09.4366667+00:00

    Before diving it, it should be noted that the Bing maps consumer site (bing.com/maps) does not use the Bing Maps V8 SDK anymore. That site moved to Azure Maps a couple of years ago. Azure Maps has a lot more rendering capabilities. Additionally, the consumer site is known to have a lot of functionality that isn't typically exposed through the developer APIs for various reasons (license restrictions, low requests from dev community thus not a priority to expose and maintain...). Also, the Bing Maps consumer site uses a different routing service, which may have different data and route calculation logic that differs from the older Bing Maps directions service.

    There is no built-in functionality for showing traffic along a route in the Bing Maps Directions Manager. Digging through the direction manager data, it doesn't provide any traffic information for sections of the route path through the API. I do however see in the network trace that the raw REST response for the directions request does include traffic information for sections of the route path, but this information is not exposed in the directions manager. This means there are a few paths forward:

    1. Use the REST API's directly, or in combination with the directions manager. However, to get the traffic information for sections of the route you have to use an undocumented feature (unsupported) which is to add routepathannotations into the routeAttributes option (&ra=routepath,routepathannotations). This will then add a annotations property to the route path information of the response that tells you what indices of the route path has traffic.
    2. Rather than making a second call to the directions service like in #1 and have to deal with possible misalignment in data, you could try and intercept the REST request and capture the response. I attempted to do this but for some reason I'm not seeing any requests going through the fetch API. Digging deeper I managed to find some undocumented way to get the raw route response from the directions manager directionsManager._directionsTask.getDirectionsResponse(). I've managed to get a sample together. You can try it here: https://rbrundritt.azurewebsites.net/Demos/BingMaps/TrafficAlongRoute.html Here is the source code:
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
        <style type='text/css'>
            body {
                margin: 0;
                padding: 0;
                overflow: hidden;
            }
    
            #myMap {
                position: relative;
                float:left;
                width: calc(100vw - 380px);
                height: 100vh;
            }
    
            #sidePanel {
                position: relative;
                float: left;
                width: 380px;
                height: 100vh;
            }
    
            #directionsInputContainer {
                width: 380px;
                height: 300px;
                padding-left: 16px;
                overflow-y: auto;
            }
    
            #instructions {
                height: calc(100vh - 300px);
                overflow-y: auto;
            }
        </style>
    </head>
    <body>
        <div id="sidePanel">
            <div id="directionsInputContainer"></div>
            <div id="instructions"></div>
        </div>
    
        <div id='myMap'></div>
    
        <script type='text/javascript'>
            var map, directionsManager, trafficLayer;
    
            function loadMapScenario() {
                map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
                    center: new Microsoft.Maps.Location(47.606209, -122.332071),
                    zoom: 12
                });
    
                //Create a layer for displaying the traffic data and add to the map.
                trafficLayer = new Microsoft.Maps.Layer();
    
                //Increase the zIndex so that it renders above the route line: https://learn.microsoft.com/en-us/bingmaps/v8-web-control/articles/zindexing-in-bing-maps-v8
                trafficLayer.setZIndex(15000);
    
                map.layers.insert(trafficLayer);
    
                //Load directions manager.
                Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
                    directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
    
                    // Set Route Mode to driving
                    directionsManager.setRequestOptions({
                        routeMode: Microsoft.Maps.Directions.RouteMode.driving,
    
                        //Ensure that we request a route that has traffic data in it.
                        routeOptimization: 'timeWithTraffic'
                    });
                    var waypoint1 = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond', location: new Microsoft.Maps.Location(47.67683029174805, -122.1099624633789) });
                    var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle', location: new Microsoft.Maps.Location(47.59977722167969, -122.33458709716797) });
                    directionsManager.addWaypoint(waypoint1);
                    directionsManager.addWaypoint(waypoint2);
    
                    directionsManager.showInputPanel('directionsInputContainer');
    
                    // Set the element in which the itinerary will be rendered
                    directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('instructions') });
    
                    //Add an event to listen for updates.
                    Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () {
                        //Clear the traffic layer.
                        trafficLayer.clear();
    
                        //Get the current route index.
                        var routeIdx = directionsManager.getRequestOptions().routeIndex;
    
                        //Get the current route.
                        var currentRoute = directionsManager._directionsTask.getDirectionsResponse().resourceSets[0].resources[routeIdx];
    
                        //Get the route path info.
                        var routePath = currentRoute.routePath;
    
                        //See if there is any route annotations.
                        if (routePath.annotations) {
                            var currentIdx = -1;
                            var currentTraffic = 'NoTraffic';
    
                            //Loop through the route path annotations.
                            routePath.annotations.forEach(a => {
                                //Only look at the traffic related annotations.
                                if (a.traffic) {
                                    //Check to see if the type of traffic has changed.
                                    if (a.traffic !== currentTraffic) {
                                        getTrafficLine(routePath, currentIdx, a.index, currentTraffic);
    
                                        currentIdx = a.index;
                                    }
    
                                    currentTraffic = a.traffic;
                                }
                            });
    
                            //If there is still a line in progress, add it to the layer.
                            if (currentIdx !== routePath.line.coordinates.length) {
                                getTrafficLine(routePath, currentIdx, routePath.line.coordinates.length, currentTraffic);
                            }
                        }
                    });
    
                    directionsManager.calculateDirections();
                });
            }
    
            function getTrafficLine(routePath, startIdx, endIdx, trafficLevel) {
                //If it has changed, check to see if there is a previous index, and if so, create a line and add to traffic layer.
                //Skip if current traffic is NoTraffic or Unknown
                if (startIdx > -1 && !(trafficLevel === 'NoTraffic' || trafficLevel === 'Unknown')) {
                    var points = [];
    
                    //Get the subset of routePath points.
                    for (var i = startIdx; i < endIdx; i++) {
                        var c = routePath.line.coordinates[i];
                        points.push(new Microsoft.Maps.Location(c[0], c[1]));
                    }
    
                    //Get the color for the traffic level.
                    var color = 'green';
    
                    switch (trafficLevel) {
                        case 'Serious':
                            color = 'darkred';
                        case 'Moderate':
                            color = 'red';
                            break;
                        case 'Minor':
                            color = 'orange';
                            break;
                        case 'LowImpact':
                        default:
                            break;
                    }
    
                    //Create a line from the currentIdx to a.index.
                    var line = new Microsoft.Maps.Polyline(points, { strokeColor: color, strokeThickness: 5 })
                    trafficLayer.add(line);
                }
            }
        </script>
        <script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=<YOUR_BING_MAPS_KEY>&callback=loadMapScenario' async defer></script>
    </body>
    </html>
    

    Just in case you missed the notice, Bing Maps is being retired in June 2028 for paid enterprise accounts (free basic accounts are already retired). The main code sample site for Bing Maps was redirected to Azure Maps a while ago. Most developers requesting assistance with Bing Maps these days are usually looking for assistance with migrating to Azure Maps.

    If you use Azure Maps, here is a sample for showing traffic along a route: https://samples.azuremaps.com/?sample=show-traffic-along-route You will need to zoom in to see it since the traffic is usually in a small section of the road. That sample site has a bunch of other traffic samples that are pretty interesting as well.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.