-
Notifications
You must be signed in to change notification settings - Fork 445
/
Census block group analysis.html
311 lines (260 loc) · 14.7 KB
/
Census block group analysis.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<!DOCTYPE html>
<html lang="en">
<head>
<title>Census block group analysis - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<link rel="shortcut icon" href="/favicon.ico"/>
<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" /><meta name="version" content="1.0" />
<meta name="screenshot" content="screenshot.jpg" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" rel="stylesheet" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/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/1/atlas-drawing.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/drawing/1/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='/lib/turf.min.js'></script>
<script>
var map, stateDataSource, blockDataSource, censusBlocks, geoIdPopTable, selectedStateIdx = -1;
var censusBlockKmlUrl = '/data/USCensus2010/BlockGroups/cb_2013_{stateId}_bg_500k.kmz';
var censusBlockStatsUrl = '/data/USCensus2010/BlockGroupPopulation/CenPop2010_Mean_BG{stateId}.txt';
function getMap() {
//Initialize a map instance.
map = new atlas.Map('myMap', {
style:'grayscale_light',
view: 'Auto',
//Add authentication details for connecting to Azure Maps.
authOptions: {
//Use Microsoft Entra ID authentication.
authType: 'anonymous',
clientId: 'e6b6ab59-eb5d-4d25-aa57-581135b927f0', //Your Azure Maps client id for accessing your Azure Maps account.
getToken: function (resolve, reject, map) {
//URL to your authentication service that retrieves an Microsoft Entra ID Token.
var tokenServiceUrl = 'https://samples.azuremaps.com/api/GetAzureMapsToken';
fetch(tokenServiceUrl).then(r => r.text()).then(token => resolve(token));
}
//Alternatively, use an Azure Maps key. Get an Azure Maps key at https://azure.com/maps. NOTE: The primary key should be used as the key.
//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('/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="/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>Census block group analysis</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>