Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
300 lines (251 sloc) 14 KB
<!DOCTYPE html>
<html lang="en">
<head>
<title>Census block group analysis - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<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="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>
<!-- Add reference to the Azure Maps Spatial IO module. -->
<script src="https://atlas.microsoft.com/sdk/javascript/spatial/0/atlas-spatial.js"></script>
<!-- Load turf.js a spatial math library. https://turfjs.org/ -->
<script src='https://npmcdn.com/@turf/turf/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.
atlas.setDomain('atlas.azure.us');
//Initialize a map instance.
map = new atlas.Map('myMap', {
view: 'Auto',
//Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: '<Your Azure Maps Key>'
}
});
//Wait until the map resources are ready.
map.events.add('ready', function () {
//Create a data source for state boundaries.
stateDataSource = new atlas.source.DataSource();
map.sources.add(stateDataSource);
//Add layer to outline the selected state.
map.layers.add(new atlas.layer.LineLayer(stateDataSource, null, {
strokeColor: [
'case',
['all', ['has', 'isSelected'], ['get', 'isSelected']],
'black',
'transparent'
]
}));
//Create a data source for census block data.
blockDataSource = new atlas.source.DataSource();
map.sources.add(blockDataSource);
//Add layers for rendering the census blocks that are selected.
map.layers.add([
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.
map.events.add('drawingmodechanged', drawingManager, drawingModeChanged);
//Monitor for when a polygon drawing has been completed.
map.events.add('drawingcomplete', drawingManager, analyizeSearchArea);
//Load the US state data.
stateDataSource.importDataFromUrl('/Common/data/geojson/US_States_500k.json');
});
}
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')) {
drawingManager.getSource().clear();
blockDataSource.clear();
}
}
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: atlas.data.BoundingBox.fromData(states[i]), padding: 50 });
break;
}
}
loadState(stateFP);
}
}
function loadState(stateId) {
censusBlocks = null;
drawingManager.getSource().clear();
blockDataSource.clear();
document.getElementById('loadingIcon').style.display = '';
document.getElementById('aggregateStats').innerHTML = 'Loading census data...';
Promise.all([
atlas.io.read(censusBlockKmlUrl.replace('{stateId}', stateId)),
atlas.io.read(censusBlockStatsUrl.replace('{stateId}', stateId))
]).then(values => {
//Store the census block data.
censusBlocks = values[0];
var data = values[1];
//Header: STATEFP,COUNTYFP,TRACTCE,BLKGRPCE,POPULATION,LATITUDE,LONGITUDE
//GEOID: {STATEFP}{COUNTYFP}{TRACTCE}{BLKGRPCE}
//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.');
return;
}
var poly = searchArea.toJson();
//If the search area is a circle, create a polygon from its circle coordinates.
if (searchArea.isCircle()) {
poly = new atlas.data.Polygon([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);
}
intersects.push(intersection);
}
}
//Display the itersected census block group areas.
blockDataSource.setShapes(intersects);
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: atlas.data.BoundingBox.fromData(poly), padding: 50 });
}
</script>
<style>
.big-number {
text-align: center;
font-size: 24px;
font-weight: bold;
width: 100%;
margin: 10px 0;
}
</style>
</head>
<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;">
State:
<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>
</select>
<br /><br />
<div id="aggregateStats"></div>
</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:
<ul>
<li><a href="https://www.census.gov/geographies/mapping-files/2013/geo/kml-cartographic-boundary-files.html" target="_blank">Block Group Cartographic Boundary Files</a></li>
<li><a href="https://www.census.gov/geographies/reference-files/time-series/geo/centers-population.html" target="_blank">Centers of Population by Block Group</a></li>
</ul>
</fieldset>
</body>
</html>
You can’t perform that action at this time.