-
Notifications
You must be signed in to change notification settings - Fork 447
/
Animate a choropleth map.html
286 lines (235 loc) · 12.6 KB
/
Animate a choropleth map.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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animate a Choropleth Map - 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 shows how to create a choropleth map and animate it over time." />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, thematic, choropleth, heatmap, heat map, animation, animate, animations, county, population, data-driven, data driven styling, temporal, temporal analysis" />
<meta name="author" content="Microsoft Azure Maps" /><meta name="version" content="1.0" />
<meta name="screenshot" content="screenshot.gif" />
<!-- 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 reference to the Azure Maps Spatial IO module. -->
<script src="https://atlas.microsoft.com/sdk/javascript/spatial/0/atlas-spatial.min.js"></script>
<!-- Add reference to the animation module. -->
<script src="/lib/azure-maps/azure-maps-animations.min.js"></script>
<script>
var map, datasource, popup, maxScale = 30, colorExpressions = [], timer;
function getMap() {
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-110, 50],
zoom: 2,
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));
}
// Use an Azure Maps key. Get an Azure Maps key at https://azuremaps.com/. NOTE: The primary key should be used as the key.
//authType: 'subscriptionKey',
//subscriptionKey: '[YOUR_AZURE_MAPS_KEY]'
}
});
//Create a legend scale bar.
createLegendScaleBar();
//Wait until the map resources are ready.
map.events.add('ready', function () {
//Create a popup but leave it closed so we can update it and display it later.
popup = new atlas.Popup({
position: [0, 0]
});
//Create a data source and add it to the map.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Create an array of expressions to define the fill color based on
for (var i = 0; i <= 10; i++) {
colorExpressions.push([
'interpolate',
['linear'],
['get', 'PopChange' + i],
-maxScale, 'rgb(255,0,255)', // Magenta
-maxScale / 2, 'rgb(0,0,255)', // Blue
0, 'rgb(0,255,0)', // Green
maxScale / 2, 'rgb(255,255,0)', // Yellow
maxScale, 'rgb(255,0,0)' // Red
]);
}
//Create a layer to render the polygon data.
var polygonLayer = new atlas.layer.PolygonLayer(datasource, null, {
fillColor: colorExpressions[0]
});
map.layers.add(polygonLayer, 'labels');
//Add a mouse move event to the polygon layer to show a popup with information.
map.events.add('mousemove', polygonLayer, function (e) {
if (e.shapes && e.shapes.length > 0) {
var properties = e.shapes[0].getProperties();
var html = ['<div style="padding:10px"><b>', properties.CountyName, '</b><br />', properties.StateName, '<br />% Pop Change:<br/><table><tr><td>Year</td><td>% Change</td></tr>'];
for (var i = 0; i <= 10; i++) {
var year = 2000 + i;
html.push('<tr><td>', year, '</td><td>', properties['PopChange' + i], '%</td></tr>');
}
html.push('</table></div>');
//Update the content of the popup.
popup.setOptions({
content: html.join(''),
position: e.position
});
//Open the popup.
popup.open(map);
}
});
//Add a mouse leave event to the polygon layer to hide the popup.
map.events.add('mouseleave', polygonLayer, function (e) {
popup.close();
});
//Download population estimates for US counties and county boundary GeoJSON data.
Promise.all([
fetch('/data/US_County_2010_Population.csv').then(response => response.text()),
fetch('/data/geojson/US_County_Boundaries.json').then(response => response.json())
]).then(results => {
var csv = results[0];
//Column header: STATE,COUNTY,STNAME,CTYNAME,CENSUS2000POP,POPESTIMATE072000,POPESTIMATE072001,POPESTIMATE072002,POPESTIMATE072003,POPESTIMATE072004,POPESTIMATE072005,POPESTIMATE072006,POPESTIMATE072007,POPESTIMATE072008,POPESTIMATE072009,POPESTIMATE072010
var csvTable = new atlas.io.core.CsvReader(csv).read();
//For faster cross referencing, create lookup table for table row based on the state and county ids.
var populationInfo = {};
csvTable.forEach((x, i) => {
populationInfo[x[0] + x[1]] = i;
});
//Loop through the features in the GeoJSON file.
results[1].features.forEach(f => {
//Create the same cross reference ID as used in with the CSV data.
const id = f.properties['STATE'] + f.properties['COUNTY'];
//Check to see if there is any cross referenced data.
if(populationInfo[id]) {
//Grab the matching row of data.
let row = csvTable[populationInfo[id]];
//Get the 2000 population value.
let censusPop = parseFloat(row[4]);
var obj = {
CountyName: row[3],
StateName: row[2],
CensusPop2000: censusPop
};
//Calculate the population % difference from 2000 census, and round to 1 decimal place.
for (j = 5; j < row.length; j++) {
obj['PopChange' + (j - 5)] = Math.round((parseFloat(row[j]) / censusPop - 1) * 100 * 10) / 10;
}
Object.assign(f.properties, obj);
}
});
//Add the feature data to the data source.
datasource.add(results[1].features);
//Create an animation loop.
timer = new atlas.animations.FrameBasedAnimationTimer(colorExpressions.length, (frameIdx) => {
//Update the fill color expression for the current frame.
polygonLayer.setOptions({ fillColor: colorExpressions[frameIdx] });
//Update the year in the legend.
document.getElementsByClassName('legend-label')[0].innerText = (2000 + frameIdx) + '';
}, {
duration: 10000,
loop: true
});
document.getElementById('playPauseBtn').disabled = '';
});
});
}
function createLegendScaleBar() {
var canvas = document.getElementById('legendCanvas');
var ctx = canvas.getContext('2d');
//Create a linear gradient for the legend.
var grd = ctx.createLinearGradient(0, 0, 256, 0);
grd.addColorStop(0, 'rgb(255,0,255)'); // Magenta
grd.addColorStop(0.25, 'rgb(0,0,255)'); // Blue
grd.addColorStop(0.5, 'rgb(0,255,0)'); // Green
grd.addColorStop(0.75, 'rgb(255,255,0)'); // Yellow
grd.addColorStop(1, 'rgb(255,0,0)'); // Red
ctx.fillStyle = grd;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function togglePlayPause() {
if (timer.isPlaying()) {
timer.pause();
} else {
timer.play();
}
}
</script>
<style>
.mapContainer, #myMap {
position: relative;
width: 100%;
min-width:290px;
height: 600px;
}
.legend {
position: absolute;
bottom: 5px;
left: 5px;
width: 256px;
height: 80px;
font-family: Arial;
font-size: 12px;
background-color: rgba(255, 255, 255, 0.8);
border-radius: 5px;
padding: 5px;
}
#legendCanvas {
width: 256px;
height: 15px;
margin-top:5px;
}
.legend-mid {
margin: 0 0 0 85px;
}
.legend-max {
float: right;
}
.legend-label {
margin-left: 40px;
}
#playPauseBtn {
margin-top: 5px;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
padding: 1px 5px;
}
</style>
</head>
<body onload="getMap()">
<div class="mapContainer">
<div id="myMap"></div>
<div class="legend">
<center>Population Change Estimates 2000 - 2010</center>
<canvas id="legendCanvas"></canvas>
<span class="legend-min">-30%</span>
<span class="legend-mid">0%</span>
<span class="legend-max">30%</span>
<br />
<center><input id="playPauseBtn" type="button" value="Play/Pause" disabled="disabled" onclick="togglePlayPause()" /><span class="legend-label">2000</span></center>
</div>
</div>
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend>Animate a Choropleth Map</legend>
This sample shows how to create a choropleth map and animate it over time. A choropleth map is a thematic map in which areas are shaded or patterned in proportion to
the measurement of the statistical variable being displayed on the map, in this case the estimated % population change between 2000 and 2010 of each US county relative
to the 2000 census population data. This sample uses two data files; a GeoJSON file that contains the US county boundary data, and a CSV file that contains the population
data. This sample cross references the population data and adds it as properties of the county boundary. A simple polygon layer is used to render the data and the animation
is accomplished by changing the fill color expression over time such that it will use a different years population change value to choose a color.
This sample uses the <a href="https://docs.microsoft.com/en-us/azure/azure-maps/how-to-use-spatial-io-module" target="_blank" title="Azure Maps Spatial IO module">Azure Maps Spatial IO module</a>
and the open source <a href="https://github.com/Azure-Samples/azure-maps-animations" target="_blank" title="Azure Maps Animation module">Azure Maps Animation module</a>
</fieldset>
</body>
</html>