Skip to content
Switch branches/tags
Go to file
Cannot retrieve contributors at this time
<!DOCTYPE html>
<html lang="en">
<title>Show traffic along route - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<link rel="shortcut icon" href="/favicon.ico"/>
<meta http-equiv="x-ua-compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="This sample shows how to retrieve traffic information along a route using the <b>sectionType</b> option, and color the sections on the map. " />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, services, module, route, directions, route sections, traffic" />
<meta name="author" content="Microsoft Azure Maps" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link rel="stylesheet" href="" type="text/css" />
<script src=""></script>
<!-- Add a reference to the Azure Maps Services Module JavaScript file. -->
<script src=""></script>
<script type='text/javascript'>
var map, datasource, popup, searchURL, routeURL;
function GetMap() {
//Point the Azure Maps domain to the US Azure Gov Cloud domain.
//Initialize a map instance.
map = new atlas.Map('myMap', {
view: 'Auto',
//Add authentication details for connecting to Azure Maps.
authOptions: {
//Use Azure Active Directory authentication.
authType: 'anonymous',
clientId: 'c9f2f391-13f1-407b-a4a5-f0a241bacfbf', //Your Azure Active Directory client id for accessing your Azure Maps account.
getToken: function (resolve, reject, map) {
//URL to your authentication service that retrieves an Azure Active Directory Token.
var tokenServiceUrl = '';
fetch(tokenServiceUrl).then(r => r.text()).then(token => resolve(token));
//Alternatively, use an Azure Maps key. Get an Azure Maps key at NOTE: The primary key should be used as the key.
//authType: 'subscriptionKey',
//subscriptionKey: '<Your Azure Maps Key>'
//Use MapControlCredential to share authentication between a map control and the service module.
var pipeline = atlas.service.MapsURL.newPipeline(new atlas.service.MapControlCredential(map));
//Construct the RouteURL object and point to the US Azure Gov Cloud domain.
routeURL = new atlas.service.RouteURL(pipeline, '');
//Create the SearchURL clien and point to the US Azure Gov Cloud domain.
searchURL = new atlas.service.SearchURL(pipeline, '');
//Wait until the map resources are ready.'ready', function () {
//Create a popup for displaying route section details.
popup = new atlas.Popup();
datasource = new atlas.source.DataSource();
//Create two line layers. One for the base route line, and another for the traffic sections on top. Render these below the labels.
//Render the base route line. This will look like an outline in areas that have traffic.
new atlas.layer.LineLayer(datasource, null, {
strokeWidth: 9,
lineJoin: 'round',
lineCap: 'round',
filter: ['!', ['has', 'magnitudeOfDelay']]
}), 'labels');
//Render the traffic section data above the route line.
var sectionLayer = new atlas.layer.LineLayer(datasource, null, {
//Use an expression to style the color based on the traffics magnitiude of delay metric:
strokeColor: [
['get', 'magnitudeOfDelay'],
3, 'red',
2, 'orange',
['get', 'simpleCategory'],
//If the category of the section is a Jam, make it orange.
'JAM', 'orange',
//If the category of the section is a road closure, make it black.
'ROAD_CLOSURE', 'black',
strokeWidth: 7,
lineJoin: 'round',
lineCap: 'butt',
filter: ['has', 'magnitudeOfDelay']
//Add mouse events on the section layer so we can show a popup with details about the traffic issue.'mousemove', sectionLayer, showPopup);'touchstart', sectionLayer, showPopup);
//Close the popup on mouseout or touchend.'mouseout', sectionLayer, closePopup);'touchend', closePopup);
map.layers.add(sectionLayer, 'labels');
//Create a layer for rendering the start and end points of the route as symbols.
map.layers.add(new atlas.layer.SymbolLayer(datasource, null, {
iconOptions: {
image: ['get', 'iconImage'],
allowOverlap: true,
ignorePlacement: true
textOptions: {
textField: ['get', 'title'],
offset: [0, 1.2]
filter: ['any', ['==', ['geometry-type'], 'Point'], ['==', ['geometry-type'], 'MultiPoint']] //Only render Point or MultiPoints in this layer.
//Calculate the initial route.
async function calculateRoute() {
var start = document.getElementById('startTbx').value;
var end = document.getElementById('endTbx').value;
if (start == '' || end == '') {
alert('Invalid waypoint point specified.');
var geocodeOptions = {
limit: 1,
view: 'Auto'
//Geocode the start location.
var startResult = await searchURL.searchAddress(atlas.service.Aborter.timeout(3000), start, geocodeOptions);
if (startResult.results && startResult.results.length > 0) {
var startPoint = [startResult.results[0].position.lon, startResult.results[0]];
//Geocode the end location.
var endResult = await searchURL.searchAddress(atlas.service.Aborter.timeout(3000), end, geocodeOptions);
if (endResult.results && endResult.results.length > 0) {
var endPoint = [endResult.results[0].position.lon, endResult.results[0]];
//Calculate a route.
var directions = await routeURL.calculateRouteDirections(atlas.service.Aborter.timeout(10000), [startPoint, endPoint], {
sectionType: 'traffic', //Route option to return traffic sections.
maxAlternatives: 0
//Get the route data as GeoJSON and add it to the data source.
var data = directions.geojson.getFeatures();
var route = data.features[0];
new, {
title: start,
iconImage: 'pin-blue'
new, {
title: end,
iconImage: 'pin-red'
//Extract the traffic section data.
if ( {
var sections =;
var sectionLines = [];
//Route path could be a MultiLineString as multiple route legs (specify 3 or more waypoints) can result in multiple lines.
var routePath = route.geometry.coordinates[0];
for (var i = 0; i < sections.length; i++) {
//Only worry about traffic sections with a magnitude delay of 1 (minor) or higher.
if (sections[i].sectionType === 'TRAFFIC' && sections[i].magnitudeOfDelay >= 1) {
//Create a line for the traffic section.
//Get the coordinates from the route path for the section, startPointIndex...endPointIndex - add 1 as the end index is not included
routePath.slice(sections[i].startPointIndex, sections[i].endPointIndex + 1)
), sections[i]));
//Update the map view to center over the route.
bounds: data.bbox,
padding: 30 //Add a padding to account for the pixel size of symbols.
} else {
alert('Unable to geocode end waypoint.');
} else {
alert('Unable to geocode start waypoint.');
function showPopup(e) {
//Make sure the event occurred on a shape feature.
if (e.shapes && e.shapes.length > 0) {
map.getCanvasContainer().style.cursor = 'pointer';
var properties = e.shapes[0].getProperties();
//Update the content and position of the popup.
//Create the content of the popup.
content: `<div style="padding:10px;"><b>${properties.simpleCategory}</b><br/>Speed: ${Math.round(properties.effectiveSpeedInKmh * 0.62137119)} mph</div`,
position: e.position
//Open the popup.;
function closePopup() {
map.getCanvasContainer().style.cursor = 'grab';
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="position:absolute;top:15px;left:15px;background-color:white;padding:10px;border-radius:10px;">
<td>Start: </td>
<td><input type="text" id="startTbx" value="Seattle" /></td>
<td>End: </td>
<td><input type="text" id="endTbx" value="San Diego" /></td>
<td><input type="button" value="Calculate Route" onclick="calculateRoute()" /></td>
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend><h1 style="font-size:16px">Show traffic along route</h1></legend>
This sample shows how to retrieve traffic information along a route using the <b>sectionType</b> option, and color the sections on the map.