Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
  
  <!-- Add references to the Azure Maps Map Drawing Tools JavaScript and CSS files. -->
  <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/drawing/0/atlas-drawing.min.css" type="text/css" />
  <script src="https://atlas.microsoft.com/sdk/javascript/drawing/0/atlas-drawing.min.js"></script>

<body>
  <div id="map"></div>
  
  <img id="loadingIcon" src="https://assets.codepen.io/1717245/loadingIcon.gif" title="Loading" style="position:absolute;left:calc(50% - 25px);top:calc(50% - 25px);display:none;" />
  
  <div class="legend">
        <div style="font-size:14px;font-weight:bold;">Elevation</div>
        <div style="float:left">
            <div class="colorSquare" style="background-color:#d7191c"></div>
            <div class="colorSquare" style="background-color:#fdae61"></div>
            <div class="colorSquare" style="background-color:#ffffbf"></div>
            <div class="colorSquare" style="background-color:#a6d96a"></div>
            <div class="colorSquare" style="background-color:#1a9641"></div>
        </div>
        <div style="float:left;margin:9px 5px 0 5px;">
            <div class="colorSquare">200m</div>
            <div class="colorSquare">150m</div>
            <div class="colorSquare">100m</div>
            <div class="colorSquare">50m</div>
        </div>
    </div>
  
  <div style="position:absolute;top:0px;left:calc(50% - 100px);background-color:white;padding:5px;">Draw a line on the map</div>
</body>

</html>
              
            
!

CSS

              
                html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

#map {
  width: 100%;
  height: 100%;
}

.legend {
	position: absolute;
	top: 10px;
	right: 10px;
	background-color: white;
	border-radius: 10px;
	padding: 10px;
	font-size: 11px;
}

	.colorSquare {
		width: 16px;
		height: 16px;
		text-align: center;
	}

              
            
!

JS

              
                var map, datasource, layer, drawingManager;

var maxSampleSize = 100;
var colors = ['#1a9641', '#a6d96a', '#ffffbf', '#fdae61', '#d7191c'];
var elvSteps = 50;

var elevationLineUrl = 'https://{azMapsDomain}/elevation/line/json?api-version=1.0&lines={lines}&samples={samples}';

//Initialize a map instance.
var map = new atlas.Map('map', {
  center: [-122.335, 47.608],
  zoom: 12,
  view: 'Auto',
  //Add your Azure Maps subscription client ID to the map SDK.
  authOptions: {
    authType: "anonymous",
    clientId: "04ec075f-3827-4aed-9975-d56301a2d663", //Your Azure Maps account Client ID is required to access your Azure Maps account.

    getToken: function (resolve, reject, map) {
      //URL to your authentication service that retrieves an Azure Active Directory Token.
      var tokenServiceUrl = "https://azuremapscodesamples.azurewebsites.net/Common/TokenService.ashx";

      fetch(tokenServiceUrl).then(r => r.text()).then(token => resolve(token));
    }
  }
});

//Wait until the map resources are ready.
map.events.add('ready', function () {
  //Add a style control to the map.
  map.controls.add(new atlas.control.StyleControl({
    mapStyles: 'all'
  }), {
    position: 'top-left'
  });

  //Create a data source for the route line.
  datasource = new atlas.source.DataSource(null, {
    lineMetrics: true   //Enable line metrics on the data source. This is needed to enable support for strokeGradient.
  });
  map.sources.add(datasource);

  //Create a layer for rendering the line gradient.
  layer = new atlas.layer.LineLayer(datasource, null, {
    strokeWidth: 7,
    lineJoin: 'round',
    lineCap: 'round'
  });
  map.layers.add([
    //Optionally. Add a second line layer behind the gradient layer. This layer will provide a board around the line so it is easier to see the details.
    new atlas.layer.LineLayer(datasource, null, {
      strokeWidth: 9,
      strokeColor: 'black',
      lineJoin: 'round',
      lineCap: 'round'
    }),

    layer
  ]);

  //Create an instance of the drawing manager and display the line drawing option of the drawing toolbar.
  drawingManager = new atlas.drawing.DrawingManager(map, {
    toolbar: new atlas.control.DrawingToolbar({
      buttons: ['draw-line'],
      position: 'top-left',
      style: 'light'
    })
  });

  ///Clear the map and drawing canvas when the user enters into a drawing mode.
  map.events.add('drawingmodechanged', drawingManager, drawingModeChanged);

  //Monitor for when a line drawing has been completed.
  map.events.add('drawingcomplete', drawingManager, getElevations);
});

function drawingModeChanged(mode) {
  //Clear the drawing canvas and data source.
  if (mode.startsWith('draw')) {
    drawingManager.getSource().clear();
    datasource.clear();
  }
}

function getElevations(line) {
  //Exit drawing mode and clear the drawing canvas.
  drawingManager.setOptions({ mode: 'idle' });
  drawingManager.getSource().clear();

  //Get the coordinates from the drawn line.
  var lineCoords = line.getCoordinates();

  //Round coordinates to 6 decimal places (~10cm accuracy) to reduce the length of URLs.
  lineCoords.forEach(c => {
    c[0] = Math.round(c[0] * 1000000) / 1000000;
    c[1] = Math.round(c[1] * 1000000) / 1000000;
  });

  //Get the total length of the path.
  var totalLength = atlas.math.getLengthOfPath(lineCoords);

  //Format line coordinates as "longitude0,latitude0|longitude1,latitude1|..."
  var lineParam = lineCoords.map(c => c.join(',')).join('|');

  //The elevation dataset has a 24 meter sample spacing. 
  var sampleSize = Math.min(Math.round(totalLength / 24), maxSampleSize);

  var url = elevationLineUrl.replace('{lines}', lineParam).replace('{samples}', sampleSize);	

  //Show loading icon.
  document.getElementById('loadingIcon').style.display = '';


  processRequest(url).then(response => {
    if (response.error) {
      alert(response.error.message);
      return;
    }

    //Convert response into array of positions: [longitude, latitude, elevation]
    var points = response.data.map(c => [c.coordinate.longitude, c.coordinate.latitude, c.elevationInMeter]);

    //Generate a data driven style expression for a gradient based on the elevation.
    var exp = calculateElevationGradientExpression(points, totalLength);

    layer.setOptions({ strokeGradient: exp });
    datasource.setShapes([line]);

    //Hide loading icon.
    document.getElementById('loadingIcon').style.display = 'none';
  });
}

function calculateElevationGradientExpression(points, totalLength) {
  var exp = [
    'interpolate',  //This will cause the colors from each data point to create a gradient between points.
    ['linear'],
    ['line-progress']
  ];

  //The line progress will be a fraction of the total length of the path,
  //so we can calculate the line progress value of each data point and set the color accordingly.
  var progress = 0;

  for (var i = 0; i < points.length; i++) {
    var elv = points[i][2];

    //Elevation may not be available sometimes. Skip these values.
    if (elv !== 'NaN') {
      //The line progress value is a value between 0 and 1. 
      //Taking the travelled distance and dividing it by the total distance of the path, will give us the line progress value.
      exp.push(progress / totalLength);

      //Add our business logic on how a data point should be colored based on the elevation.

      //Calculate the index in the color array based on the elevation step size.
      var colorIdx = Math.max(0, Math.min(Math.round(elv / elvSteps), colors.length - 1));
      exp.push(colors[colorIdx]);

      if (i < points.length - 1) {
        progress += atlas.math.getDistanceTo(points[i], points[i + 1]);
      }
    }
  }

  return exp;
}

function processRequest(url) {
  return new Promise((resolve, reject) => {
    //Replace the domain placeholder to ensure the same Azure Maps cloud is used throughout the app.
    url = url.replace('{azMapsDomain}', atlas.getDomain());

    //Get the authentication details from the map for use in the request.
    var requestParams = map.authentication.signRequest({ url: url });

    //Transform the request.
    var transform = map.getServiceOptions().tranformRequest;
    if (transform) {
      requestParams = transform(request);
    }

    fetch(requestParams.url, {
      method: 'GET',
      mode: 'cors',
      headers: new Headers(requestParams.headers)
    })
      .then(r => r.json(), e => reject(e))
      .then(r => {
      resolve(r);
    }, e => reject(e));
  });
}

              
            
!
999px

Console