Skip to content
Switch branches/tags
Go to file
Cannot retrieve contributors at this time
<!DOCTYPE html>
<html lang="en">
<title>Draw gridded polygon - 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 calculate a gridded pattern within a drawn polygon based on a physical distances. " />
<meta name="keywords" content="map, gis, api, sdk, drawing tools, circle, rectangle, polygon, paint, events" />
<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 references to the Azure Maps Map Drawing Tools JavaScript and CSS files. -->
<link rel="stylesheet" href="" type="text/css" />
<script src=""></script>
<!-- Load turf.js a spatial math library. -->
<script src='/Common/scripts/turf.min.js'></script>
<script type='text/javascript'>
var map, datasource, drawingManager;
function GetMap() {
//Point the Azure Maps domain to the US Azure Gov Cloud domain.
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-122.33, 47.6],
zoom: 12,
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>'
});'ready', function () {
//Create a drawing manager and add the toolbar with the polygon drawing button to the input panel.
drawingManager = new atlas.drawing.DrawingManager(map, {
toolbar: new atlas.control.DrawingToolbar({
buttons: ['draw-polygon'],
containerId: 'drawingBtnContainer'
});'drawingcomplete', drawingManager, function (evt) {
var input = document.querySelector("#cellSize");
if (input.valueAsNumber === NaN) {
alert('Cell size not set.');
} else if (evt && drawingManager.getOptions().mode !== 'idle') {
//Get the drawn shape from the map and
var feature = new;
//Calculate the grid cells.
calculateGrid(input.valueAsNumber, feature);
//Remove the drawn shape from the map.
//Create a data source to store the grid cells.
datasource = new atlas.source.DataSource();
//Create layers to render the grid cells.
new atlas.layer.LineLayer(datasource, null, {
strokeColor: 'black',
strokeWidth: 1
new atlas.layer.PolygonLayer(datasource, null, {
fillOpacity: 0.5,
fillColor: '#ff0000'
//Add functionality for the clear button.
document.querySelector('#clear').addEventListener('click', function () {
function calculateGrid(cellSize, feature) {
//Put the drawing manager into an idle state.
drawingManager.setOptions({ mode: "idle" });
//Check for kinks in the drawn feature.
var kinks = turf.kinks(feature);
if (kinks.features.length > 0) {
//If there are self-intersections, buffer by 0 to get rid of them
feature = turf.buffer(feature, 0, { units: 'meters' });
//Calculate the bounding box of the feature.
var bb =;
//Get the grid shape.
var gridShapeElm = document.getElementById('gridShape');
var gridShape = gridShapeElm.options[gridShapeElm.selectedIndex].innerText;
//Get the selected grid algorithm.
var gridAlgo = turf.squareGrid;
switch (gridShape) {
case 'triangle':
gridAlgo = turf.triangleGrid;
case 'hexagon':
gridAlgo = turf.hexGrid;
//Get the cell size units.
var unitsElm = document.getElementById('units');
var units = unitsElm.options[unitsElm.selectedIndex].innerText;
//Convert meters or feet to a supported unit value.
if (units === 'meters') {
cellSize /= 1000;
units = 'kilometers';
} else if (units === 'feet') {
cellSize *= 0.0002;
units = 'miles';
//Buffer the bounding box to account for overlap at edges.
var bboxBuffer = 0;
switch (units) {
case 'miles':
bboxBuffer = cellSize / 69 * 2; //Approximately 69 miles per degree at the equator.
case 'kilometers':
bboxBuffer = cellSize / 111 * 2; //Approximately 111 KM's per degree at the equator.
case 'radians':
bboxBuffer = cellSize * 360 / Math.PI;
case 'degrees':
bboxBuffer = cellSize * 2;
var c =;
var height =;
var width =;
bb =, width + bboxBuffer, height + bboxBuffer);
var intersections = [];
//Calculate the grid cells.
const grid = gridAlgo(bb, cellSize, {
mask: feature,
units: units
//Loop through and calculate the intersection of each grid cell with the feature.
if (grid.features.length > 0) {
for (var i = 0, len = grid.features.length; i < len; i++) {
var intersection = turf.intersect(grid.features[i], feature);
if (intersection) {
//Add the grid cells to the data source.
if (intersections.length > 0) {
} else {
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="padding:1rem;position:absolute;top:1rem;left:1rem;background-color:white;border-radius:0.2rem;padding:10px; box-shadow: hsl(0, 0%, 80%) 0.2em 0.2em 0.2em;">
Grid cell shape:
<select id="gridShape">
<option selected="selected">square</option>
<br /><br />
Cell size units:
<select id="units">
<option selected="selected">miles</option>
<br /><br />
Cell size <input placeholder="Cell size" type="number" id="cellSize" />
<br /><br />
<button id="clear">Clear</button>
<span id="drawingBtnContainer" style="float:right;border:1px solid #ccc;"></span>
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend><h1 style="font-size:16px">Draw gridded polygon</h1></legend>
This sample shows how to calculate a gridded pattern within a drawn polygon based on a physical distances.
For gridded patterns that are based on pixel distances, use a fill pattern with a polygon.
This sample uses the open source <a href="" target="_blank">Turf.js</a> library to for some of the spatial calculation.