Skip to content
Switch branches/tags
Go to file
Cannot retrieve contributors at this time
<!DOCTYPE html>
<html lang="en">
<title>Census block group analysis - 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 loads census block group data for a state and then retrieves the intersection with an area drawn by the user and calculates an estimated population." />
<meta name="keywords" content="Microsoft maps, map, gis, API, spatial analysis, spatial join, Voronoi, Voronoi diagram, within, intersects, intersection, spatial data, spatial io module, geoxml, census" />
<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>
<!-- Add reference to the Azure Maps Spatial IO module. -->
<script src=""></script>
<!-- Load turf.js a spatial math library. -->
<script src='/Common/scripts/turf.min.js'></script>
<script type='text/javascript'>
var map, stateDataSource, blockDataSource, censusBlocks, geoIdPopTable, selectedStateIdx = -1;
var censusBlockKmlUrl = '/Common/data/USCensus2010/BlockGroups/cb_2013_{stateId}_bg_500k.kmz';
var censusBlockStatsUrl = '/Common/data/USCensus2010/BlockGroupPopulation/CenPop2010_Mean_BG{stateId}.txt';
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>'
//Wait until the map resources are ready.'ready', function () {
//Create a data source for state boundaries.
stateDataSource = new atlas.source.DataSource();
//Add layer to outline the selected state.
map.layers.add(new atlas.layer.LineLayer(stateDataSource, null, {
strokeColor: [
['all', ['has', 'isSelected'], ['get', 'isSelected']],
//Create a data source for census block data.
blockDataSource = new atlas.source.DataSource();
//Add layers for rendering the census blocks that are selected.
new atlas.layer.PolygonLayer(blockDataSource, null, {
fillColor: 'deepskyblue'
new atlas.layer.LineLayer(blockDataSource, null, {
strokeColor: '#F535AA'
], 'labels');
//Create an instance of the drawing manager and display the drawing toolbar.
drawingManager = new atlas.drawing.DrawingManager(map, {
toolbar: new atlas.control.DrawingToolbar({
buttons: ['draw-polygon', 'draw-rectangle', 'draw-circle'],
position: 'top-right',
style: 'light'
//Clear the map and drawing canvas when the user enters into a drawing mode.'drawingmodechanged', drawingManager, drawingModeChanged);
//Monitor for when a polygon drawing has been completed.'drawingcomplete', drawingManager, analyizeSearchArea);
//Load the US state data.
function drawingModeChanged(mode) {
//Clear the drawing canvas when the user enters into a drawing mode and reset the style of all pins.
if (mode.startsWith('draw')) {
function stateChanged() {
//When the state changes, load the data for that state.
var stateFP = document.getElementById('stateFipCodes').value;
document.getElementById('aggregateStats').innerHTML = '';
if (selectedStateIdx !== -1) {
stateDataSource.getShapes()[selectedStateIdx].properties.isSelected = false;
if (stateFP !== '') {
//Highlight the selected state.
var states = stateDataSource.getShapes();
for (var i = 0; i < states.length; i++) {
if (states[i].getProperties().STATE === stateFP) {
states[i].setProperties({ isSelected: true });
//Focus the map over the state.
map.setCamera({ bounds:[i]), padding: 50 });
function loadState(stateId) {
censusBlocks = null;
document.getElementById('loadingIcon').style.display = '';
document.getElementById('aggregateStats').innerHTML = 'Loading census data...';
Promise.all(['{stateId}', stateId)),'{stateId}', stateId))
]).then(values => {
//Store the census block data.
censusBlocks = values[0];
var data = values[1];
//Create a lookup table of population by GEOID.
geoIdPopTable = {};
for (var i = 0; i < data.features.length; i++) {
var p = data.features[i].properties;
geoIdPopTable[`${p.STATEFP}${p.COUNTYFP}${p.TRACTCE}${p.BLKGRPCE}`] = parseFloat(p.POPULATION);
document.getElementById('loadingIcon').style.display = 'none';
document.getElementById('aggregateStats').innerHTML = '';
function analyizeSearchArea(searchArea) {
//Exit drawing mode.
drawingManager.setOptions({ mode: 'idle' });
if (!censusBlocks) {
alert('Census block data for a state must be loaded first.');
var poly = searchArea.toJson();
//If the search area is a circle, create a polygon from its circle coordinates.
if (searchArea.isCircle()) {
poly = new[searchArea.getCircleCoordinates()]);
var intersects = [];
var estimatedPop = 0;
for (var i = 0; i < censusBlocks.features.length; i++) {
//Check to see if the census block is a polygon and touches the search area.
if (censusBlocks.features[i].geometry.type === 'Polygon' && !turf.booleanDisjoint(poly, censusBlocks.features[i])) {
//Calculate the intersection of the search area to with census block group.
var intersection = turf.intersect(poly, censusBlocks.features[i]);
//Get the population from the GEOID of the census block.
var population = geoIdPopTable[censusBlocks.features[i].properties.GEOID.value];
if (population) {
//Calculate estimated popuplation by using the area of intersection compared to the area of the census block (land + water) multiplied by the population for the census block.
var area = atlas.math.getArea(intersection, 'squareMeters');
estimatedPop += population * Math.min(area / (parseFloat(censusBlocks.features[i].properties.ALAND.value) + parseFloat(censusBlocks.features[i].properties.AWATER.value)), 1);
//Display the itersected census block group areas.
document.getElementById('aggregateStats').innerHTML = `Estimated Population<div class="big-number">${Math.round(estimatedPop).toLocaleString()}</div># of census block groups<div class="big-number">${intersects.length.toLocaleString()}</div>`;
//Focus the map over the search area.
map.setCamera({ bounds:, padding: 50 });
.big-number {
text-align: center;
font-size: 24px;
font-weight: bold;
width: 100%;
margin: 10px 0;
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="position:absolute;top:10px;left:10px;background-color:white;padding:10px;border-radius:10px;">
<select id="stateFipCodes" onchange="stateChanged()">
<option value=""></option>
<option value="01">Alabama</option>
<option value="02">Alaska</option>
<option value="04">Arizona</option>
<option value="05">Arkansas</option>
<option value="06">California</option>
<option value="08">Colorado</option>
<option value="09">Connecticut</option>
<option value="10">Delaware</option>
<option value="11">District of Columbia</option>
<option value="12">Florida</option>
<option value="13">Georgia</option>
<option value="15">Hawaii</option>
<option value="16">Idaho</option>
<option value="17">Illinois</option>
<option value="18">Indiana</option>
<option value="19">Iowa</option>
<option value="20">Kansas</option>
<option value="21">Kentucky</option>
<option value="22">Louisiana</option>
<option value="23">Maine</option>
<option value="24">Maryland</option>
<option value="25">Massachusetts</option>
<option value="26">Michigan</option>
<option value="27">Minnesota</option>
<option value="28">Mississippi</option>
<option value="29">Missouri</option>
<option value="30">Montana</option>
<option value="31">Nebraska</option>
<option value="32">Nevada</option>
<option value="33">New Hampshire</option>
<option value="34">New Jersey</option>
<option value="35">New Mexico</option>
<option value="36">New York</option>
<option value="37">North Carolina</option>
<option value="38">North Dakota</option>
<option value="39">Ohio</option>
<option value="40">Oklahoma</option>
<option value="41">Oregon</option>
<option value="42">Pennsylvania</option>
<option value="44">Rhode Island</option>
<option value="45">South Carolina</option>
<option value="46">South Dakota</option>
<option value="47">Tennessee</option>
<option value="48">Texas</option>
<option value="49">Utah</option>
<option value="50">Vermont</option>
<option value="51">Virginia</option>
<option value="53">Washington</option>
<option value="54">West Virginia</option>
<option value="55">Wisconsin</option>
<option value="56">Wyoming</option>
<br /><br />
<div id="aggregateStats"></div>
<img id="loadingIcon" src="../Common/images/loadingIcon.gif" title="Loading" style="position:absolute;left:calc(50% - 25px);top:250px;display:none;" />
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend><h1 style="font-size:16px">Census block group analysis</h1></legend>
This sample loads census block group data for a state and then retrieves the intersection with an area drawn by the user and calculates an estimated population.
Not only does it take into consideration the population of each census block group, but also the amount of overlap they have with the drawn area as well. <br /><br />
US Census 2010 data used in this sample:
<li><a href="" target="_blank">Block Group Cartographic Boundary Files</a></li>
<li><a href="" target="_blank">Centers of Population by Block Group</a></li>