-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsofia.html
462 lines (385 loc) · 14.8 KB
/
sofia.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
<!DOCTYPE html>
<html>
<head>
<title>Изборни резултати по секции, София</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
<style>
body, html {
height: 100%;
margin: 0;
padding: 0;
}
#map {
width: 100%;
height: 100%;
}
.map-container {
position: relative;
width: 100vw;
height: 100vh;
}
.dropdown-container {
position: absolute;
top: 10px;
left: 50px;
background-color: rgba(255, 255, 255, 0.8);
padding: 5px;
border-radius: 5px;
z-index: 1000;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
.show-info-button {
position: absolute;
top: 80px;
left: 10px;
width: 35px;
height: 35px;
z-index: 900;
background: white;
border-radius: 5px;
cursor: pointer;
text-align: center;
line-height: 30px;
font: 14px/16px Arial, Helvetica, sans-serif;
}
#infoBox {
position: absolute;
top: 50px;
left: 20px;
z-index: 1000;
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
display: none;
font: 14px/16px Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<div class="map-container">
<div id="map"></div>
<div class="dropdown-container">
<select id="csvDropdown">
<option value="oct19r1">Окт 2019 Местни (1ви тур, ОС)</option>
<option value="oct19">Окт 2019 Местни (2ри тур, кмет)</option>
<option value="apr21" selected>Апр 2021 НС</option>
<option value="jul21">Юли 2021 НС</option>
<option value="nov21">Ное 2021 НС</option>
<option value="oct22">Окт 2022 НС</option>
<option value="apr23">Апр 2023 НС</option>
<option value="oct23r1">Окт 2023 (1ви тур, кмет)</option>
<option value="oct23r1OS">Окт 2023 (1ви тур, ОС)</option>
<option value="oct23r2">Окт 2023 (2ри тур, кмет)</option>
<option value="jun24">Юни 2024 НС</option>
</select>
<br>
<select id="columnsDropdown"></select>
</div>
<button id="showInfo" class="show-info-button">i</button>
<div id="infoBox" class="info-box" style="display:none;">
Изборните данни са от <a href=https://results.cik.bg>ЦИК</a>.<br>
Инструменти за анализ:<a href=https://bg-izbori.herokuapp.com/>bg-izbori.herokuapp.com</a>.<br>
Границите на секциите са предоставени от <a href=https://data-for-good.bg/>"Данни за добро"</a>.<br>
За коментари и намерени грешки: <a href=https://twitter.com/petar_baka>@petar_baka</a>.<br>
<button onclick="showInfoBox()">Затвори</button>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
let csvData;
let geojsonData;
let map;
let geojsonLayer;
var info = L.control();
let selectedColumn = 'ГЕРБ-СДС';
document.getElementById("csvDropdown").addEventListener("change", function(event) {
updateGeojson(event).then(populateDropdown);
});
document.getElementById('showInfo').addEventListener('click', showInfoBox);
loadGeoJSON('apr21').then(initializeMap);
function loadCSV(el_date) {
const csvFilename = "../../assets/data/mestni/sofia_" + el_date + "_pct.csv";
return new Promise((resolve, reject) => {
Papa.parse(csvFilename, {
download: true,
header: true,
dynamicTyping: true,
complete: (result) => {
csvData = result.data;
resolve(result);
},
error: (error) => {
reject(error);
}
});
});
}
function updateGeojson(event) {
const el_date = event.target.value;
return loadGeoJSON(el_date)
.then(() => {
map.removeLayer(geojsonLayer);
geojsonLayer = L.geoJson(geojsonData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
})
.catch(error => {
console.error("Failed to load new GeoJSON data:", error);
});
}
function loadGeoJSON(el_date) {
const jsonFile = "../../assets/data/mestni/sofia_" + el_date + ".json";
console.log(jsonFile);
return fetch(jsonFile)
.then((response) => response.json())
.then((data) => {
geojsonData = data;
return loadCSV(el_date);
});
}
function matchData(columnName) { // TODO: get rid of this (no need to add data to the GeoJSON features; you can fetch data dynamically from the csv as needed)
geojsonData.features.forEach((feature) => {
const match = csvData.find((row) => ('0' + row.id).slice(-9) === feature.properties.sid);
if (match) {
//console.log(match, columnName)
feature.properties[columnName] = match[columnName];
feature.properties['total'] = match['total'];
feature.properties['eligible_voters'] = match['eligible_voters'];
feature.properties['активност'] = match['активност'];
} else {
console.log('no match ', columnName)
feature.properties[columnName] = NaN;
feature.properties['total'] = NaN;
feature.properties['eligible_voters'] = NaN;
feature.properties['активност'] = NaN;
}
});
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties[selectedColumn]),
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties, selectedColumn);
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function resetHighlight(e) {
geojsonLayer.resetStyle(e.target);
info.update(undefined, selectedColumn);
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature,
dbclick: function(e) {
highlightFeature(e);
zoomToFeature(e);
}
});
}
function initializeMap() {
map = L.map('map').setView([42.691, 23.333], 12);
var tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>|<a href="https://twitter.com/petar_baka">petar_baka</a>|<a href="https://data-for-good.bg/">Данни за добро</a>'
}).addTo(map);
geojsonLayer = L.geoJson(geojsonData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props, selectedColumn) {
var selectedYear = document.getElementById('csvDropdown');
var selectedYearText = selectedYear.options[selectedYear.selectedIndex].textContent;;
var table = '';
var textbox = '<h4>Резултати ' + selectedColumn + ' (' + selectedYearText + ')</h4>';
if (props) {
table = generateTableHtmlForRowById(props.sid);
textbox += '<b>Секция ' + props.sid + '</b><br>';
if (selectedColumn !== 'активност') {
textbox += selectedColumn + ' гласове: ' + Math.round(props[selectedColumn]*props['total']) + '<br>'
} else {
// TODO: breakdown valid votes, invalid votes, total
// TODO: breakdown initial voter list, added to voter list, total
textbox += 'Общо валидни гласове: ' + Math.round(props[selectedColumn]*props['eligible_voters']) + '<br>'
textbox += 'Избиратели по списък: ' + props['eligible_voters'] + '<br>'
}
textbox += selectedColumn + ` (%): ${isNaN(props[selectedColumn]) ? props[selectedColumn] : (100*props[selectedColumn]).toFixed(1)}<br>`
textbox += table + '<br>'
textbox += 'Общо валидни гласове: ' + props['total'] + '<br>'
textbox += 'Избиратели по списък: ' + props['eligible_voters'] + '<br>'
textbox += `Валидни гласове/избиратели по списък: ${isNaN(props['активност']) ? props['активност'] : props['активност'].toFixed(2)}<br>`
} else {
textbox += 'Посочете секция.'
};
this._div.innerHTML = textbox;
};
info.addTo(map);
var legend = L.control({position: 'bottomleft'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend');
var grades = [0, .1, .2, .3, .4, .5, .6, .7, .8];
var labels = [];
var from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 0.0001) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br>');
return div;
};
legend.addTo(map);
populateDropdown();
document.getElementById("columnsDropdown").addEventListener("change", updateColumn);
}
function populateDropdown() {
const dropdown = document.getElementById("columnsDropdown");
const columns = Object.keys(csvData[0]);
let parties = [];
const excluded = ['id', 'eligible_voters', 'total'];
dropdown.innerHTML = '';
columns.forEach((column) => {
if (! excluded.includes(column)) {
const option = document.createElement("option");
option.value = column;
option.textContent = column;
dropdown.appendChild(option);
parties.push(column)
}
});
if ((selectedColumn == null) || !( columns.includes(selectedColumn))) {
selectedColumn = parties[0];
} else if (columns.includes(selectedColumn)) {
dropdown.value = selectedColumn;
};
matchData(selectedColumn);
geojsonLayer.setStyle(feature => {
return {
fillColor: getColor(feature.properties[selectedColumn]),
};
});
info.update(undefined, selectedColumn);
}
function updateColumn(event) {
selectedColumn = event.target.value;
matchData(selectedColumn);
geojsonLayer.setStyle(feature => {
return {
fillColor: getColor(feature.properties[selectedColumn]),
};
});
info.update(undefined, selectedColumn);
}
function generateTableHtmlForRowById(targetId) {
const targetRow = csvData.find((row) => ('0000000' + row.id).slice(-9) === targetId);
if (!targetRow) return '';
let html = '<table>';
html += '<thead><tr>';
html += '<th>Партия/Кандидат</th>';
html += '<th>Гласове</th>';
html += '<th>Гласове/<br>общо валидни</th>';
html += '</tr></thead>';
html += '<tbody><tr>';
for (let key in targetRow) {
if (key !== "total" && key !== "id" && key !== 'eligible_voters' && key !== 'активност') {
const originalValue = targetRow[key];
const multipliedValue = originalValue * targetRow.total;
html += `<tr>`;
html += `<td>${key}</td>`;
html += `<td>${Math.round(multipliedValue)}</td>`;
html += `<td>${isNaN(originalValue) ? originalValue : originalValue.toFixed(2)}</td>`;
html += `</tr>`;
}
}
html += '</tr></tbody>';
html += '</table>';
return html;
}
function interpolateColor(color1, color2, factor) {
const r = Math.round(color1[0] + factor * (color2[0] - color1[0]));
const g = Math.round(color1[1] + factor * (color2[1] - color1[1]));
const b = Math.round(color1[2] + factor * (color2[2] - color1[2]));
return `rgb(${r}, ${g}, ${b})`;
}
function getColor(d) {
const colors = [ // check out https://colorbrewer2.org/?type=sequential&scheme=YlOrRd&n=9
[255,255,204],
[255,237,160],
[254,217,118],
[254,178,76],
[253,141,60],
[252,78,42],
[227,26,28],
[189,0,38],
[128,0,38]
];
if (isNaN(d)) return 'rgb(255,255,204)';
if (d <= 0) return 'rgb(255,255,204)';
if (d >= 0.8) return 'rgb(128,0,38)';
const index = Math.floor(d * 10);
const factor = (d * 10) - index;
return interpolateColor(colors[index], colors[index + 1], factor);
}
function showInfoBox() {
var infoBox = document.getElementById('infoBox');
if (infoBox.style.display === 'none') {
infoBox.style.display = 'block';
} else {
infoBox.style.display = 'none';
}
}
</script>