-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1241 lines (1083 loc) · 50.5 KB
/
index.js
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// IMPORTS
///////////////////////////////////////////////////////////////////////////////////////////////////////////
const Promise = require('es6-promise-polyfill').Promise;
///////////////////////////////////////////////////////////////////////////////////
// STYLES, in production, these will be written to <script> tags
///////////////////////////////////////////////////////////////////////////////////
// import './loading.css';
import styles from './index.scss';
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES & STRUCTURES
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// global config
const CONFIG = {};
const DATA = {};
// basemap definitions, no options here, just a single set of basemap tiles and labels above features. see initMap();
CONFIG.basemaps = {
'hybrid': L.gridLayer.googleMutant({ type: 'hybrid', pane: 'hybrid' }),
'satellite': L.gridLayer.googleMutant({ type: 'satellite', pane: 'satellite' }),
'basemap' : L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png', { attribution: '©OpenStreetMap, ©CARTO', pane: 'basemap' }),
'labels': L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_only_labels/{z}/{x}/{y}@2x.png', { pane: 'labels' }),
};
// specify which basemap will be on by default, and when the map is reset by the 'Reset' button
CONFIG.default_basemap = 'basemap';
// default title for results
CONFIG.default_title = 'Worldwide';
// outerring, used for constructing the mask, see searchCountry();
CONFIG.outerring = [[-90,-360],[-90,360],[90,360],[90,-360],[-90,-360]];
// minzoom and maxzoom for the map
CONFIG.minzoom = 2;
CONFIG.maxzoom = 17;
// Style definitions (see also scss exports, which are imported here as styles{})
// a light grey mask covering the entire globe
CONFIG.maskstyle = { stroke: false, fillColor: '#999', fillOpacity: 0.2, className: 'mask' };
// style for highlighting countries on hover and click
CONFIG.country_hover_style = { stroke: false, fillColor: '#fffef4', fillOpacity: 0.9 };
CONFIG.country_selected_style = { stroke: false, fillColor: '#fff', fillOpacity: 1 };
// an "invisible" country style, as we don't want countries to show except on hover or click
CONFIG.country_no_style = { opacity: 0, fillOpacity: 0 };
// primary attributes to display: used for searching, displaying individual results on map popups, etc.
CONFIG.attributes = {
'id': {name: 'Tracker ID'},
'unit': {name: 'Unit'},
'plant': {name: 'Plant name'},
'plant_local': {name: 'Plant name (local)'},
'url': {name: 'Wiki page'},
'owner': {name: 'Owner'},
'parent': {name: 'Parent'},
'capacity': {name: 'Capacity (MW)'},
'status': {name: 'Status'},
'region': {name: 'Region'},
'country': {name: 'Country'},
'subnational': {name: 'Subnational unit (province/state)'},
'year': {name: 'Start year'},
};
// the Universe of status types: these are the categories used to symbolize coal plants on the map
// key: allowed status names, matching those used in DATA.fossil_data
// text: human readible display
// color: imported from CSS
CONFIG.status_types = {
'announced': {'id': 0, 'text': 'Announced', 'color': styles.status1 },
'pre-permit': {'id': 1, 'text': 'Pre-permit', 'color': styles.status2 },
'permitted': {'id': 2, 'text': 'Permitted', 'color': styles.status3 },
'construction': {'id': 3, 'text': 'Construction', 'color': styles.status4 },
'shelved': {'id': 4, 'text': 'Shelved', 'color': styles.status5 },
'retired': {'id': 5, 'text': 'Retired', 'color': styles.status6 },
'cancelled': {'id': 6, 'text': 'Cancelled', 'color': styles.status7 },
'operating': {'id': 7, 'text': 'Operating', 'color': styles.status8 },
'mothballed': {'id': 8, 'text': 'Mothballed', 'color': styles.status9 },
};
// used to keep a list of markers showing for a particular country or place, by status
// allows us to 'filter' markers, e.g. show/hide using FilterMarkers method added to leaflet.prunecluster.js
// ** IMPORTANT: ensure that these keys match the keys in CONFIG.status_types exactly
// NOTE: Keep in order by status type id (above), otherwise the clusters "pie charts" will not get the correct color
CONFIG.status_markers = {
'announced': {'markers': []},
'pre-permit': {'markers': []},
'permitted': {'markers': []},
'construction': {'markers': []},
'shelved': {'markers': []},
'retired': {'markers': []},
'cancelled': {'markers': []},
'operating': {'markers': []},
'mothballed': {'markers': []},
};
// Note: prunecluster.markercluster.js needs this, and I have not found a better way to provide it
CONFIG.markercluster_colors = Object.keys(CONFIG.status_types).map(function(v) { return CONFIG.status_types[v].color });
// search fields for various categories. These are selected by values keyed select#search-category
CONFIG.search_categories = {
'all': ['unit', 'plant', 'parent', 'region', 'country', 'subnational', 'year'],
'unit': ['unit', 'plant'],
'parent': ['owner','parent'],
'location': ['region', 'country', 'subnational'],
'year': ['year'],
}
// the placeholder to show, also depends on the select#search-category selection
CONFIG.search_placeholder = {
'all': 'project name, company, country',
'unit': 'unit name, plant name',
'parent': 'company name',
'location': 'place name',
'year': 'year (e.g. 2010)',
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///// INITIALIZATION: these functions are called when the page is ready,
///////////////////////////////////////////////////////////////////////////////////////////////////////////
$(document).ready(function () {
// data initialization first, then the remaining init steps
Promise.all([initData('./data/trackers.json'),
initData('./data/countries.json'),
initData('./data/companies.txt'),
])
.then(function(data) {
initDataFormat(data) // get data ready for use
initButtons(); // init button listeners
initTabs(); // init the main navigation tabs.
initSearch(); // init the full text search
initMap(); // regular leaflet map setup
initTable(); // init the DataTable table
initMapLayers(); // init some map layers and map feature styles
initStatusCheckboxes(); // initialize the checkboxes to turn on/off trackers by status
initPruneCluster(); // init the prune clustering library
initSearchBar(); // init viewport-specific search bar behavior
initState(); // init app state given url options
// ready!
setTimeout(function () {
$(window).trigger('resize');
$('div#pleasewait').hide();
}, 300);
}); // Promise.then()
});
// listen for changes to the window size and resize the map
$(window).resize(function() {
// resize the map, table and content divs to fit the current window
resize();
})
// resize everything: map, content divs, table
function resize() {
// calculate the content height for this window:
// 42px for the nav bar, 10px top #map, 10px top of #container = 42 + 20 + 10
var winheight = $(window).height();
var height = winheight - 54;
// resize the map
$('div#map').height(height - 8);
CONFIG.map.invalidateSize();
// resize the content divs to this same height
$('div.content').height(height);
// resize the table body
// guesstimate a good scrollbody height; dynamic based on the window height
var tablediv = $('.dataTables_scrollBody');
if (!tablediv.length) return;
// starting value
var value = $(window).width() < 768 ? 273 : 265;
// differential sizing depending on if there is a horizontal scrollbar or not
if (tablediv.hasHorizontalScrollBar()) value += 10;
var height = $('body').height() - value;
// set the scrollbody height via css property
tablediv.css('height', height);
CONFIG.table.columns.adjust().draw();
}
// init some viewport-specific search bar behavior
function initSearchBar() {
var category = $('select#search-category').val();
var placeholder = CONFIG.search_placeholder[category];
var search = $('input#mapsearch');
var width = $(window).width();
if (width < 768) {
if (search.hasClass('collapsed')) return;
search.addClass('collapsed');
setTimeout(function() { search.attr('placeholder','') }, 300);
search.siblings().find('span.glyphicon-search').on('click', function() {
search.toggleClass('collapsed');
if (search.hasClass('collapsed')) {
setTimeout(function() {
search.attr('placeholder','');
search.val('');
}, 300);
} else {
search.attr('placeholder',placeholder);
// search.off('click');
}
});
} else {
search.removeClass('collapsed');
search.attr('placeholder',placeholder);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions called on doc ready
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Basic data init, returns a promise
function initData(url) {
// wrap this in a promise, so we know we have it before continuing on to remaining initialize steps
return new Promise(function(resolve, reject) {
$.get(url, function(data) {
resolve(data);
});
});
}
// data parsing and formatting, once data are on-board
function initDataFormat(data) {
// keep a reference to the tracker data JSON
DATA.tracker_data = data[0];
// set country data equal to the second data object from the initData() Promise()
DATA.country_data = data[1];
// organize company data into an array of companies
DATA.companies = data[2].split('\n');
}
// init state from allowed params, or not
function initState() {
// if we have url params, get the params and use them to set state
if (window.location.search) {
// get the params. These are mutually exclusive at this point, and very special case,
// e.g. one partner wants to display a map of Germany, another wants a map of Africa, and so on
let params = new URLSearchParams(window.location.search);
// country param. In principal, should support any matching country name
if (params.has('country')) {
let country = params.get('country');
if (country) {
// find the country, zoom to it
CONFIG.countries.eachLayer(function(layer) {
if (layer.name == country ) {
let bounds = layer.getBounds();
searchCountry(country, bounds, 2000);
highlightCountryLayer(layer.feature);
}
})
}
}
// region param. Currently this only supports one term "Africa"
if (params.has('region')) {
// check that this is equal to 'Africa'
let region = params.get('region');
if (region.toLowerCase() === 'africa') {
// nothing too special here, fit the map to Africa
// let bounds = L.latLngBounds([35.919, 63.466],[-35.3,-17.537]);
// render({ force_redraw: true, fitbounds: false });
// CONFIG.map.fitBounds(bounds);
// console.log(CONFIG);
// a list of african conunties for which to compile totals
// TODO: Shouldn't we just list all African countries here? Future updates might include a country not on this list
// the problem is, no way a-prior to know what country name GEM will use
let africa_country_list = ['Botswana','Democratic Republic of Congo','Egypt','Ghana','Guinea','Ivory Coast','Kenya','Madagascar','Malawi','Mauritius','Morocco','Mozambique','Namibia','Niger','Nigeria','Reunion','Senegal','South Africa','Sudan','Eswatini','Tanzania','Zambia','Zimbabwe'];
// set a name for the info panel
let name = 'Africa'
// get the data for this predefined collection of African countries, *only* for updating the results panel
// the map and table, continue to show all data
var data = [];
// search the data for matches to the country name
DATA.tracker_data.forEach(function(feature) {
// look for matching names in feature.properties.countries
if (africa_country_list.indexOf(feature.country) > -1) data.push(feature);
});
// because we are not filtering the map, but only changing the bounds
// results on the map can easily get out of sync due to a previous search filter
// so first we need to explicity render() the map with all data, but not the table or results
render({ name: name, map: true, results: false, table: false, fitbounds: false });
// THEN update results panel for *this* country data only
updateResultsPanel(data, name);
// THEN the table, with all data, but not with this name
// may seem superfluous, but important to keep the map/table in sync, and showing all data
drawTable(DATA.tracker_data);
// zoom the map to africa
let bounds = L.latLngBounds([35.919, 63.466],[-35.3,-17.537]);
setTimeout(function() {
CONFIG.map.fitBounds(bounds);
}, 2000);
} else {
// we have an undefined region
resetTheMap();
}
}
// no params
} else {
// the default init, if we don't have matching params
resetTheMap();
}
}
function initButtons() {
// "reset" button that resets the map
$('div a#reset-button').on('click', function(){
resetTheMap();
});
// search icons on the search forms, click to submit
$('form.search-form span.glyphicon-search').on('click', function() {
// shouldn't really be needed, since this submits on keyup()
// and definitely not on mobile, as it interferes with the form exapanding
if ( !isMobile() ) {
$(this).closest('form').submit();
}
});
// close button, generically closes it's direct parent
$('div.close').on('click', function() { $(this).parent().hide(); });
// init the menu icon to open the "results" panel
$('div#results-icon').on('click', function() { $('div#country-results').show(); });
// the clear search button, clears the search input
$('div.searchwrapper a.clear-search').on('click', function() {
$(this).siblings('input').val('').trigger('keyup');
$('div#suggestions').hide();
$(this).hide();
DATA.filtered = null;
});
// hide, but don't clear suggestions "menu" when clicking outside of it
$(document).click(function(event) {
var $target = $(event.target);
if(!$target.closest('div#suggestions').length &&
$('div#suggestions').is(":visible")) {
$('div#suggestions').hide();
}
});
// init the zoom button that shows on the modal details for an individual coal plant
$('#btn-zoom').click(function(){
var target = this.dataset.zoom.split(',');
var latlng = L.latLng([target[0], target[1]]);
var zoom = 16;
// remove current basemap
removeCurrentBasemap();
// add google satellite basemap
CONFIG.map.addLayer(CONFIG.basemaps['satellite']);
// ...and keep the radio button in sync with the map
$('#layers-base input[data-baselayer="satellite"]').prop('checked', true);
// remove any country "highlight" and select effect, as this will block the map
CONFIG.countries.setStyle(CONFIG.country_no_style);
CONFIG.selected_country.name = '';
CONFIG.selected_country.layer.clearLayers();
// add the back button, which takes the user back to previous view (see function goBack() defined in the construction of Leaflet control)
// but only if there is not already a back button on the map
CONFIG.oldbounds = CONFIG.map.getBounds();
if ($('.btn-back').length == 0) CONFIG.back.addTo(CONFIG.map);
// move and zoom the map to the selected unit
CONFIG.map.setView(latlng, zoom);
});
// a leaflet control to take the user back to where they came
// Only visible when zooming to an individual plant from the dialog popup. See $('#btn-zoom').click()
L.backButton = L.Control.extend({
options: {
position: 'bottomleft'
},
onAdd: function (map) {
var container = L.DomUtil.create('div', 'btn btn-primary btn-back', container);
container.title = 'Click to go back to the previous view';
this._map = map;
// generate the button
var button = L.DomUtil.create('a', 'active', container);
button.control = this;
button.href = 'javascript:void(0);';
button.innerHTML = '<span class="glyphicon glyphicon-chevron-left"></span> Go back to country view';
L.DomEvent
.addListener(button, 'click', L.DomEvent.stopPropagation)
.addListener(button, 'click', L.DomEvent.preventDefault)
.addListener(button, 'click', function () {
this.control.goBack();
});
// all set, L.Control API is to return the container we created
return container;
},
// the function called by the control
goBack: function () {
// set the map to the previous bounds
CONFIG.map.fitBounds(CONFIG.oldbounds);
// remove current basemap
removeCurrentBasemap();
// add the plain basemap - we could try to keep track of which basemap the user
// was on before zooming in - but what if they zoom in to another? then the current
// basemap becomes satellite - and tracking all this gets ridiculous
CONFIG.map.addLayer(CONFIG.basemaps.basemap);
CONFIG.map.addLayer(CONFIG.basemaps.labels);
// keep the radio button in sync with the map
$('#layers-base input[data-baselayer="basemap"]').prop('checked', true);
// remove the back button
CONFIG.back.remove(CONFIG.map);
}
});
// select all/none by status
$('div#layer-control-clear span#select-all').on('click', function(e) {
$('div#status-layers input:not(:checked)').each(function(c) { $(this).click() });
return false;
});
$('div#layer-control-clear span#clear-all').on('click', function(e) {
$('div#status-layers input:checked').each(function(c) { $(this).click() });
return false;
});
}
// initialize the map in the main navigation map tab
function initMap() {
// basic leaflet map setup
CONFIG.map = L.map('map', {
attributionControl:false,
zoomControl: false,
minZoom: CONFIG.minzoom, maxZoom: CONFIG.maxzoom,
attributionControl: false,
});
// add zoom control, top right
L.control.zoom({
position:'topright'
}).addTo(CONFIG.map);
// map panes
// - create panes for basemaps
CONFIG.map.createPane('basemap');
CONFIG.map.getPane('basemap').style.zIndex = 300;
CONFIG.map.getPane('basemap').style.pointerEvents = 'none';
CONFIG.map.createPane('hybrid');
CONFIG.map.getPane('hybrid').style.zIndex = 301;
CONFIG.map.getPane('hybrid').style.pointerEvents = 'none';
CONFIG.map.createPane('satellite');
CONFIG.map.getPane('satellite').style.zIndex = 302;
CONFIG.map.getPane('satellite').style.pointerEvents = 'none';
CONFIG.map.createPane('labels');
CONFIG.map.getPane('labels').style.zIndex = 475;
CONFIG.map.getPane('labels').style.pointerEvents = 'none';
// - create map panes for county interactions, which will sit between the basemap and labels
CONFIG.map.createPane('country-mask');
CONFIG.map.getPane('country-mask').style.zIndex = 320;
CONFIG.map.createPane('country-hover');
CONFIG.map.getPane('country-hover').style.zIndex = 350;
CONFIG.map.createPane('country-select');
CONFIG.map.getPane('country-select').style.zIndex = 450;
CONFIG.map.createPane('feature-pane');
CONFIG.map.getPane('feature-pane').style.zIndex = 550;
// add attribution
var credits = L.control.attribution().addTo(CONFIG.map);
credits.addAttribution('Interactive mapping by <a href="http://greeninfo.org" target="_blank">GreenInfo Network</a>. Data: <a href="https://globalenergymonitor.org/" target="_blank">Global Energy Monitor</a>');
// Add a feature group to hold the mask, essentially a grey box covering the world minus the country in the view
CONFIG.mask = L.featureGroup([L.polygon(CONFIG.outerring)], {pane: 'country-mask' }).addTo(CONFIG.map);
CONFIG.mask.setStyle(CONFIG.maskstyle);
// Add a layer to hold countries, for click and hover (not mobile) events on country features
CONFIG.countries = L.featureGroup([], { pane: 'country-hover' }).addTo(CONFIG.map);
L.geoJson(DATA.country_data,{ style: CONFIG.country_no_style, onEachFeature: massageCountryFeaturesAsTheyLoad });
// add a layer to hold any selected country
CONFIG.selected_country = {};
CONFIG.selected_country.layer = L.geoJson([], {style: CONFIG.country_selected_style, pane: 'country-select'}).addTo(CONFIG.map);
// add a feature group to hold the clusters
CONFIG.cluster_layer = L.featureGroup([], {pane: 'feature-pane' }).addTo(CONFIG.map);
// once the map is done loading, resize
CONFIG.map.on('load', function() {
resize();
CONFIG.map.invalidateSize();
});
// create an instance of L.backButton()
CONFIG.back = new L.backButton() // not added now, see initButtons()
// zoom listeners
CONFIG.map.on('zoomend', function() {
let zoom = CONFIG.map.getZoom();
});
}
function initMapLayers() {
// on startup, add the basemap and labels
CONFIG.map.addLayer(CONFIG.basemaps.basemap);
CONFIG.map.addLayer(CONFIG.basemaps.labels);
// set listener on radio button change to change to the selected basemap
// and also control whether or not the mask is showing
$('#layers-base input').change(function() {
var selected = $(this).data().baselayer;
// remove current basemap and labels
removeCurrentBasemap();
// add selected basemap and labels, if necessary
CONFIG.map.addLayer(CONFIG.basemaps[selected]);
if (selected == 'basemap') CONFIG.map.addLayer(CONFIG.basemaps.labels);
// make room for the attribution
if (selected == 'satellite') {
$('div.layer-control[data-panel="layers"]').css('bottom', '42px');
} else {
$('div.layer-control[data-panel="layers"]').css('bottom', '22px');
}
});
}
// set listener on checkboxes to turn on/off trackers by status, and update the clusters
function initStatusCheckboxes() {
$('div.layer-control').on('change', '#status-layers input', function() {
var status = $(this).val();
// 1) update the markers on the map
var markers = CONFIG.status_markers[status].markers;
CONFIG.clusters.FilterMarkers(markers, !$(this).prop('checked')); // false to filter on, true to filter off :)
CONFIG.clusters.ProcessView();
// 2) update the rows shown on the table
let statuses = [];
$('div.layer-control div#status-layers input:checked').each(function(l) {
statuses.push(this.value);
});
// filter the current set of filtered data, or all data if there is no current filter applied
let data_to_filter = DATA.filtered || DATA.tracker_data;
var filtered = data_to_filter.filter(function(d) {
return statuses.indexOf(d.status) > -1
})
drawTable(filtered, 'Status filtered');
// 3) update the "results" panel
updateResultsPanel(filtered, 'Status filtered');
});
}
// init the data table, but don't populate it, yet
function initTable() {
// set up the table column names we want to use in the table
var columns = $.map(CONFIG.attributes, function(value){ return value; });
// set up formatted column names for the table
var names = Object.keys(CONFIG.attributes);
// don't include column for url; we're going to format this as a link together with the unit name
var index = $.inArray('url',names);
columns.splice(index, 1);
names.splice(index, 1);
CONFIG.table_names = names;
// put table column names into format we need for DataTables
var colnames = [];
$.each(columns, function(k, value) {
// set up an empty object and push a sTitle keys to it for each column title
var obj = {};
obj['title'] = value.name;
colnames.push(obj);
});
// initialize and keep a reference to the DataTable
CONFIG.table = $('#table-content table').DataTable({
data : [],
// include the id in the data, but not searchable, nor displayed
columnDefs : [{targets:[0], visible: false, searchable: false}],
columns : colnames,
autoWidth : true,
scrollY : "1px", // initial value only, will be resized by calling resize();
scrollX : true,
lengthMenu : [50, 100, 500],
iDisplayLength : 100, // 100 has a noticable lag to it when displaying and filtering; 10 is fastest
dom : 'litp',
deferRender : true, // default is false
});
} // init table
// initialize the nav tabs: what gets shown, what gets hidden, what needs resizing, when these are displayed
// important: to add a functional tab, you must also include markup for it in css, see e.g. input#help-tab:checked ~ div#help-content {}
function initTabs() {
$('input.tab').on('click', function(e) {
// get the type from the id
var type = e.currentTarget.id.split("-")[0];
switch (type) {
case 'map':
CONFIG.map.invalidateSize(false);
$('form.search-form').show();
break;
case 'table':
$('form.search-form').show();
resize();
break;
default:
// hide search form
$('form.search-form').hide();
break;
}
});
}
// A collection of things to init that support searching
function initSearch() {
// when clicking on a "suggestion", put that text in the search input and search
$('div#suggestions').on('click', 'div.suggestion', function() {
var query = this.innerText;
$('form#search input').val(query);
searchForText();
$('div#suggestions').hide();
});
// update the placeholder text when search category is selected
$('select#search-category').on('change', function() {
let value = $(this).val();
let placeholder = CONFIG.search_placeholder[value];
// clear any search string on the search and update the placeholder
$('input#mapsearch').attr('placeholder', placeholder);
// empty and hide the "suggestions" div
$('div#suggestions').empty().hide();
});
// init the "map search" form input itself
$('form#search input').keyup(_.debounce(function() {
// if the input is cleared, show all results
// this is distinct from the case of "No results", in searchForText
if (!this.value) return resetTheMap();
// otherwise, just trigger the search
$(this).submit();
},300));
$('form#search').submit(function(e) {
// prevent default, and return early if we submitted an empty form
e.preventDefault();
if (! $('form#search input#mapsearch').val()) return;
// search the map, and that process will update the table
searchForText();
})
}
// initialize the PruneClusters, and override some factory methods
function initPruneCluster() {
// create a new PruceCluster object, with a minimal cluster size of (30)
// updated arg to 30; seems to really help countries like China/India
CONFIG.clusters = new PruneClusterForLeaflet(30);
CONFIG.map.addLayer(CONFIG.clusters);
// this is from the categories example; sets ups cluster stats used to derive category colors in the clusters
CONFIG.clusters.BuildLeafletClusterIcon = function(cluster) {
var e = new L.Icon.MarkerCluster();
e.stats = cluster.stats;
e.population = cluster.population;
return e;
};
var pi2 = Math.PI * 2;
L.Icon.MarkerCluster = L.Icon.extend({
options: {
iconSize: new L.Point(22, 22),
className: 'prunecluster leaflet-markercluster-icon'
},
createIcon: function () {
// based on L.Icon.Canvas from shramov/leaflet-plugins (BSD licence)
var e = document.createElement('canvas');
this._setIconStyles(e, 'icon');
var s = this.options.iconSize;
e.width = s.x;
e.height = s.y;
this.draw(e.getContext('2d'), s.x, s.y);
return e;
},
createShadow: function () {
return null;
},
draw: function(canvas, width, height) {
// the pie chart itself
var start = 0;
for (var i = 0, l = CONFIG.markercluster_colors.length; i < l; ++i) {
// the size of this slice of the pie
var size = this.stats[i] / this.population;
if (size > 0) {
canvas.beginPath();
canvas.moveTo(11, 11);
canvas.fillStyle = CONFIG.markercluster_colors[i];
// start from a smidgen away, to create a tiny gap, unless this is a single slice pie
// in which case we don't want a gap
var gap = size == 1 ? 0 : 0.15
var from = start + gap;
var to = start + size * pi2;
if (to < from) {
from = start;
}
canvas.arc(11,11,11, from, to);
start = start + size*pi2;
canvas.lineTo(11,11);
canvas.fill();
canvas.closePath();
}
}
// the white circle on top of the pie chart, to make the middle of the "donut"
canvas.beginPath();
canvas.fillStyle = 'white';
canvas.arc(11, 11, 7, 0, Math.PI*2);
canvas.fill();
canvas.closePath();
// the text label count
canvas.fillStyle = '#555';
canvas.textAlign = 'center';
canvas.textBaseline = 'middle';
canvas.font = 'bold 9px sans-serif';
canvas.fillText(this.population, 11, 11, 15);
}
});
// we override this method: don't force zoom to a cluster on click (the default)
CONFIG.clusters.BuildLeafletCluster = function (cluster, position) {
var _this = this;
var m = new L.Marker(position, {
icon: this.BuildLeafletClusterIcon(cluster)
});
// this defines what happen when you click a cluster, not the underlying icons
m.on('click', function () {
var markersArea = _this.Cluster.FindMarkersInArea(cluster.bounds);
var b = _this.Cluster.ComputeBounds(markersArea);
if (b) {
// skip the force zoom that is here by default, instead, spiderfy the overlapping icons
_this._map.fire('overlappingmarkers', { cluster: _this, markers: markersArea, center: m.getLatLng(), marker: m });
}
});
return m;
}
// we override this method to handle clicks on individual plant markers (not the clusters)
CONFIG.clusters.PrepareLeafletMarker = function(leafletMarker, data){
var html = `<div style='text-align:center;'><strong>${data.title}</strong><br><div class='popup-click-msg'>Click the circle for details</div></div>`;
leafletMarker.bindPopup(html);
leafletMarker.setIcon(data.icon);
leafletMarker.attributes = data.attributes;
leafletMarker.coordinates = data.coordinates;
leafletMarker.on('click',function () {
openTrackerInfoPanel(this);
});
leafletMarker.on('mouseover', function() {
this.openPopup();
});
leafletMarker.on('mouseout', function() { CONFIG.map.closePopup(); });
}
// A convenience method for marking a given feature as "filtered" (e.g. not shown on the map and removed from a cluster)
CONFIG.clusters.FilterMarkers = function (markers, filter) {
for (var i = 0, l = markers.length; i < l; ++i) {
// false to add, true to remove
markers[i].filtered = filter;
}
};
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Named functions
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set up all map layers for all types and statuses, and set up layer objects in CONFIG.status_types['layers'], so we can turn them on and off later.
function drawMap(data, force_redraw=false, fitbounds=true) {
// step 1: clear the marker clustering system and repopulate it with the current set of tracker points
// as we go through, log what statuses are in fact seen; this is used in step 5 to show/hide checkboxes for toggling trackers by status
var statuses = [];
var trackers = [];
data.forEach(function (tracker) {
var status = tracker.status;
if (status) {
// log that this status has been seen, see step 3 below
if (statuses.indexOf(status) < 0) statuses.push(status);
// add the feature to the trackers list for the table
trackers.push(tracker);
}
});
// step 2: update the marker clustering, now that "trackers" is implicitly filtered to everything that we need
updateClusters(trackers, fitbounds);
// step 3: hide the status toggle checkboxes, showing only the ones which in fact have a status represented
drawLegend(statuses);
}
function updateClusters(data, fitbounds) {
// start by clearing out existing clusters
CONFIG.clusters.RemoveMarkers();
// iterate over the data and set up the clusters
data.forEach(function(feature) {
// the "status" of the tracker point affects its icon color
// and also its membership in CONFIG.status_markers for per-status filtering
var status = feature.status;
var statusId = CONFIG.status_types[status]['id'];
var cssClass = `status${statusId + 1}`;
var marker = new PruneCluster.Marker(parseFloat(feature.lat), parseFloat(feature.lng), {
title: feature.plant,
icon: L.divIcon({
className: 'circle-div ' + cssClass, // Specify a class name we can refer to in CSS.
iconSize: [15, 15] // Set the marker width and height
})
});
// get the attributes for use in the custom popup dialog (see openTrackerInfoPanel())
marker.data.attributes = feature;
// get the lat-lng now so we can zoom to the plant's location later
// getting the lat-lng of the spider won't work, since it gets spidered out to some other place
// tip: the raw dataset is lng,lat and Leaflet is lat,lng
marker.data.coordinates = [ feature.lat, feature.lng ];
// set the category for PruneCluster-ing
marker.category = parseInt(statusId);
// These have all defaulted to visible for a long time now... do we need this??
// furthermore, if the marker shouldn't be visible at first, filter the marker by setting the filtered flag to true (=don't draw me)
// if (!CONFIG.status_types[status].visible) marker.filtered = true;
// register the marker for PruneCluster clustering
CONFIG.clusters.RegisterMarker(marker);
// also add the marker to the list by status, so we can toggle it on/off in the legend
// see CONFIG.map.on('overlayadd') and CONFIG.map.on('overlayremove')
CONFIG.status_markers[status].markers.push(marker);
});
// all set! process the view, and fit the map to the new bounds
CONFIG.clusters.ProcessView();
var cluster_bounds = CONFIG.clusters.Cluster.ComputeGlobalBounds();
if (cluster_bounds) {
var bounds = [[cluster_bounds.minLat, cluster_bounds.minLng],[cluster_bounds.maxLat, cluster_bounds.maxLng]];
} else {
// we have no clusters (empty result)!
bounds = CONFIG.homebounds;
}
// fit the map to the bounds, if instructed
if (fitbounds) {
// timeout appears necessary to let the clusters do their thing, before fitting bounds
setTimeout(function() {
// typically we'll just do this (e.g. on search)
CONFIG.map.fitBounds(bounds);
// first load: a trick to always fit the bounds in the map, see #20
if (! CONFIG.homebounds) {
let center = CONFIG.map.getCenter();
let zoom = CONFIG.map.getBoundsZoom(bounds, true); // finds the zoom where bounds are fully contained
CONFIG.map.setView([center.lat, center.lng], zoom);
CONFIG.map.once("moveend zoomend", function() {
// wait til this animation is complete, then set homebounds
CONFIG.homebounds = CONFIG.map.getBounds();
});
}
}, 200)
}
}
// show and hide the correct legend labels and checkboxes for this set of data and statuses
// "statuses" comes from the data search itself
function drawLegend(statuses) {
$('#status-layer-wrapper').show();
var target = $('#status-layers').html(''); // clear existing html
statuses.forEach(function(status) {
var label = $('<label>');
var input = $('<input>', {
type: 'checkbox',
value: status
}).attr('checked','checked');
input.appendTo(label);
var container = $('<span>', {'class': 'legend-container'}).appendTo(label);
// adds colored circle to legend
var div = $('<div>', {
style: 'background:' + CONFIG.status_types[status].color,
'class': 'circle'
}).appendTo(container);
// adds text to legend
var innerSpan = $('<span>', {
text: ' ' + CONFIG.status_types[status].text
}).appendTo(container);
label.appendTo(target);
});
}
// update the DataTable
function drawTable(trackers, title) {
// set up the table data
var data = [];
trackers.forEach(function(tracker) {
// make up a row entry for the table: a list of column values.
// and copy over all columns from [CONFIG.table_names] as is to this row
var row = [];
$.each(CONFIG.table_names, function(i,name) {
// we've already got 'Unit' formatted as a link, above, so skip this here
if (name=='unit') return;
row.push(tracker[name]);
});
// Add project name as url to the wiki page
row.splice(1,0,`<a href="${tracker.url}" target="_blank" title="click to open the Wiki page for this project">${tracker.unit}</a>`);
// when that's all done, push the row as another [] to data
data.push(row);
});
// purge and reinitialize the DataTable instance
CONFIG.table.clear();
CONFIG.table.rows.add(data);
CONFIG.table.search('').draw();
// update the table name, if provided
var text = title ? title : CONFIG.default_title;
$('div#table h3 span').text(text);
}
// update the "results" panel that sits above the map
// this always shows either the Global tally of things, or a country-specific count, or a count from a search term enterd in the "Free Search" input
function updateResultsPanel(data, country=CONFIG.default_title) {
// update primary content
$('div#country-results div#results-title h3').text(country);
var totalrow = $('div#country-results div#total-count').empty();
var totaltext = data.length > 0 ? (data.length > 1 ? `Tracking ${data.length.toLocaleString()} coal-fired units` : `Tracking ${data.length} coal project`) : `Nothing found`;
var total = $('<div>',{text: totaltext}).appendTo(totalrow);
}
// when user clicks on a coal plant point, customize a popup dialog and open it
function openTrackerInfoPanel(feature) {
// get the features properties, i.e. the data to show on the modal
var properties = feature.attributes;
// get the popup object itself and customize
var popup = $('#tracker-modal');
// go through each property for this one feature, and write out the value to the correct span, according to data-name property
$.each(properties, function(dataname, value) {
// get preferred text for each status types
if (dataname == 'status') value = CONFIG.status_types[value].text;
// write the status name to the dialog
$('#tracker-modal .modal-content span').filter('[data-name="' + dataname + '"]').text(value);
})
// wiki page needs special handling to format as <a> link
var wiki = $('#tracker-modal .modal-content a').filter('[data-name="wiki_page"]');
if (properties['url']) {
wiki.attr('href', properties['url']);
wiki.parent().show();
} else {
wiki.parent().hide();
}
// format the zoom-to button data.zoom attribute. See initZoom();
// this lets one zoom to the location of the clicked plant
var zoomButton = $('#btn-zoom');
zoomButton.attr('data-zoom', feature.attributes.lat + "," + feature.attributes.lng);
// all set: open the dialog
popup.modal();
}
// Reset "button": resets the app to default state
function resetTheMap() {
// clear anything in the search inputs
$('form.search-form input').val('');
// reset map & table display with the default search
// If we have a homebounds defined, that means we've been here before, and have rendered the full data to the map.
if (CONFIG.homebounds) {
// use homebounds we already defined
render({ force_redraw: true, fitbounds: false });
CONFIG.map.fitBounds(CONFIG.homebounds);
} else {
// first time through, let this function do the map fitting and set CONFIG.homebounds
render({ force_redraw: true });
}