forked from OnTheLine/otl-metromerger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
410 lines (363 loc) · 14.1 KB
/
index.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
<!DOCTYPE html>
<html>
<head>
<title>MetroMerger</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js"></script>
<script
src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="
crossorigin="anonymous">
</script>
<link
rel="stylesheet"
href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"
/>
<script
src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"
integrity="sha256-xLD7nhI62fcsEZK2/v8LsBcb4lG7dgULkuXoXB/j91c="
crossorigin="anonymous">
</script>
<link rel="stylesheet" href="style.css" />
<script>
$(function () {
$("#accordion").accordion({
heightStyle: "content",
});
});
</script>
</head>
<body>
<div id="map"></div>
<div id="accordion">
<h3 id="region1_title">Metro Region 1</h3>
<div>
<div id="region1_text" class="merged_stats">No towns selected</div>
<ul id="region1_list" class="towns_list"></ul>
<small><a href="javascript:export_csv()">Export results</a></small>
</div>
<h3 id="region2_title">Metro Region 2</h3>
<div>
<div id="region2_text" class="merged_stats">No towns selected</div>
<ul id="region2_list" class="towns_list"></ul>
<small><a href="javascript:export_csv()">Export results</a></small>
</div>
<h3 id="region3_title">Metro Region 3</h3>
<div>
<div id="region3_text" class="merged_stats">No towns selected</div>
<ul id="region3_list" class="towns_list"></ul>
<small><a href="javascript:export_csv()">Export results</a></small>
</div>
</div>
<script type="text/javascript">
var map = L.map("map", {
center: [41.5, -72.71],
zoom: 9,
scrollWheelZoom: false,
zoomControl: false,
});
// customize source link to your GitHub repo
map.attributionControl.setPrefix(
'View <a href="https://github.com/ontheline/otl-metromerger" target="_blank">code on GitHub</a>, created with <a href="https://leafletjs.com/" title="A JS library for interactive maps">Leaflet</a>'
);
new L.tileLayer(
"https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
{
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attribution/">Carto</a>',
}
).addTo(map);
// move zoom control different corner
new L.Control.Zoom({ position: "topright" }).addTo(map);
var geojson;
var totalPop = 0;
var totalIncome = 0;
var totalTaxable = 0;
var metroPerCapIncome = 0;
var metroPerCapTaxable = 0;
// Create 3 region-builders and arrays
var poly_colors = ["green", "blue", "purple"];
var towns = [[], [], []];
var i;
// style initial map in gray tone
function style(feature) {
return {
fillColor: "gray",
weight: 2,
opacity: 1,
color: "white",
dashArray: "3",
fillOpacity: 0.5,
};
}
// display data when hovering
function highlightFeature(e) {
var layer = e.target;
info.update(layer.feature.properties);
}
// export results to CSV for 3 regions
function export_csv() {
var csvContent = "data:text/plain;charset=utf-8,";
for (var i = 0; i < 3; i++) {
csvContent += "Region " + (i + 1) + ":\r\n";
csvContent += update_list(i, 1);
csvContent += "\r\n\r\n\r\n";
}
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "MetroMergerResults.txt");
link.click();
}
for (key in poly_colors) {
var index_for_text = parseInt(key) + 1;
$("#region" + index_for_text + "_title").css("color", poly_colors[key]);
}
// Update display list
function update_list(region, for_export) {
var region_text = "";
var total_people = 0;
var income_pc = 0;
var taxable_pc = 0;
var index_for_text = region + 1;
var towns_present = 0;
for (key in towns[region]) {
if (for_export) {
region_text += "- " + towns[region][key][0] + "\r\n";
} else {
region_text +=
"<tr>" +
"<td style='text-align: left'>" +
towns[region][key][0] +
"</td>" +
"<td style='text-align: right;'>" +
comma(towns[region][key][1]) +
"</td>" +
"<td style='text-align: right;'>$" +
comma(towns[region][key][2]) +
"</td>" +
"<td style='text-align: right;'>$" +
comma(towns[region][key][3] / towns[region][key][1]) +
"</td>" +
"</tr>";
}
total_people += towns[region][key][1];
income_pc += towns[region][key][2] * towns[region][key][1];
taxable_pc += towns[region][key][3];
towns_present = 1;
}
var metroPCIncome = income_pc / total_people;
var metroPCTaxable = taxable_pc / total_people;
if (for_export) {
var ret =
comma(checkNull(total_people, false)) +
" people\r\n$" +
comma(checkNull(metroPCIncome, false)) +
" income per capita\r\n$" +
comma(checkNull(metroPCTaxable, false)) +
" taxable property per capita\r\n\r\n" +
region_text;
return ret;
} else {
if (towns_present) {
var total =
"<tr>" +
"<td style=''>" +
"<strong>Total</strong>" +
"</td>" +
"<td style='text-align: right'>" +
comma(checkNull(total_people, false)) +
"</td>" +
"<td style='text-align: right'>$" +
comma(checkNull(metroPCIncome, false)) +
"</td>" +
"<td style='text-align: right'>$" +
comma(checkNull(metroPCTaxable, false)) +
"</td>" +
"</tr>";
$("#region" + index_for_text + "_text").html(
"<table style='border-collapse: collapse;'><tr><th>Town</th><th>Population " + datasetYear + "</th><th>Income per capita</th><th>Taxable Property per capita</th></tr>" +
region_text +
total +
"</table>"
);
} else {
$("#region" + index_for_text + "_text").html("No towns selected");
}
}
}
function chooseFeature(e) {
var layer = e.target;
var selected_region_num = $("#accordion").accordion("option", "active");
var town_id = parseInt(layer._leaflet_id);
if (layer.feature.properties.region == undefined) {
// not selected region
layer.setStyle({
fillColor: poly_colors[selected_region_num],
fillOpacity: 0.7,
});
layer.feature.properties.region = selected_region_num;
towns[selected_region_num][town_id] = [
layer.feature.properties.name,
layer.feature.properties.population,
layer.feature.properties.incomePerCapita,
layer.feature.properties.eqNetGrandList,
];
update_list(selected_region_num);
} else if (layer.feature.properties.region == selected_region_num) {
// deselect region
layer.setStyle({
fillColor: "gray",
fillOpacity: 0.5,
});
layer.feature.properties.region = undefined;
delete towns[selected_region_num][town_id];
update_list(selected_region_num);
} else {
// switch polygon to another region
layer.setStyle({
fillColor: poly_colors[selected_region_num],
fillOpacity: 0.7,
});
delete towns[layer.feature.properties.region][town_id];
towns[selected_region_num][town_id] = [
layer.feature.properties.name,
layer.feature.properties.population,
layer.feature.properties.incomePerCapita,
layer.feature.properties.eqNetGrandList,
];
update_list(layer.feature.properties.region);
update_list(selected_region_num);
layer.feature.properties.region = selected_region_num;
}
// updates display
info.update(layer.feature.properties);
}
// create ability to clear selections
function resetFeature(e) {
var layer = e.target;
geojson.resetStyle(layer);
totalPop -= layer.feature.properties.population;
totalIncome -= layer.feature.properties.incomePerCapita;
totalTaxable -= layer.feature.properties.eqNetGrandList;
metroPerCapIncome = totalIncome * totalPop;
metroPerCapTaxable = totalTaxable;
info.update(layer.feature.properties);
}
// event listeners for hovering or clicking on polygons
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
click: chooseFeature,
dblclick: resetFeature,
});
}
// Load data from Socrata via API
// https://data.ct.gov/Local-Government/Municipal-Fiscal-Indicators-Economic-and-Grand-Lis/jrwx-mxhm/about_data
// JSON URL for 2021 data (March 2024): https://data.ct.gov/resource/jrwx-mxhm.json?$select=town,july_1_2021_population,per_capita_income_calendar,equalized_net_grand_list_fye_2021
// Backup is saved to data/data.20240302.backup.json
var datasetYear = 2021; // used to update Table header and Source
var datasetUrl = 'https://data.ct.gov/Local-Government/Municipal-Fiscal-Indicators-Economic-and-Grand-Lis/jrwx-mxhm/about_data'; // used for Source only
var apiEndpoint = 'https://data.ct.gov/resource/jrwx-mxhm.json'; // used to pull data; locate dataset on Socrata, then click Export > API Endpoint
var apiDataColumns = {
'town': 'town',
'population': 'july_1_2021_population',
'incomePerCapita': 'per_capita_income_calendar',
'eqNetGrandList': 'equalized_net_grand_list_fye_2021',
};
apiEndpointFiltered = apiEndpoint + '?$select=' + Object.values(apiDataColumns).join(','); // filter API to return 4 columns only
console.log(apiEndpointFiltered); // use browser Console to see this URL; consider saving a backup copy of JSON locally
$.getJSON(apiEndpointFiltered, function(apiData) {
// Convert array of data points into a dictionary {town1 -> {data}, ...}
var town2data = {};
for (let i = 0; i < apiData.length; i++) {
town2data[ apiData[i]['town'] ] = {
'population': parseInt(apiData[i][ apiDataColumns['population'] ]),
'incomePerCapita': parseInt(apiData[i][ apiDataColumns['incomePerCapita'] ]),
'eqNetGrandList': parseInt(apiData[i][ apiDataColumns['eqNetGrandList'] ])
}
}
// Load GeoJSON with town boundaries
$.getJSON("./data/map.geojson", function (geojsonData) {
// Assign data from Socrata API to each town
for (let i = 0; i < geojsonData.features.length; i++) {
Object.assign(
geojsonData.features[i].properties,
town2data[ geojsonData.features[i].properties.name.toUpperCase() ]
);
}
geojson = L.geoJson(geojsonData, {
style: style,
onEachFeature: onEachFeature,
});
geojson.addTo(map);
});
});
// set up the info window
var info = L.control({ position: "topleft" }); // location of infobox
info.onAdd = function (map) {
this._div = L.DomUtil.create("div", "info"); // create a div with a class "info"
this.update();
return this._div;
};
// update the control info window based on feature properties passed
info.update = function (props) {
var winName = (this._div.innerHTML =
"<h4>Click to merge Connecticut towns<br />into hypothetical metro regions:</h4>" +
(props
? "<b>" + props.name +
"</b><br />" +
comma(props.population) +
" people" +
"<br />$" +
comma(props.incomePerCapita) +
" income per capita" +
"<br />$" +
comma(props.eqNetGrandList / props.population) +
" taxable property per capita" +
"<br /><span class='source'>Source: <a href='" + datasetUrl + "'>" + datasetYear + " CT Municipal Fiscal Indicators</a></span>"
: "Hover over a town"));
};
info.addTo(map);
// functions from @alvinschang at CT Mirror to display data in info window
function checkNull(val, pct) {
if (val > -99999999999) {
if (pct) {
return (val = Math.round(val * 10) / 10 + "%");
} else {
return (val = Math.round(val * 10) / 10);
}
} else {
return "No data";
}
}
function checkThePct(a) {
if (a > -1) {
return Math.round(a * 1000) / 10 + "%";
} else {
return "--";
}
}
function comma(val) {
if (isNaN(val)) {return '-'}
num = val;
val = Math.round(val);
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, "$1" + "," + "$2");
}
if (val == "-") {
return val;
} else if (num < 0) {
return "(" + val.replace("-", "") + ")";
} else {
return "" + val;
}
}
</script>
</body>
</html>