-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
331 lines (300 loc) · 9.96 KB
/
main.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
(() => {
let layerSel, selectedFtr, colorFn, $select, timeoutId;
// let dataId = 'num_apd_he';
let dataId = 'mb_all_le';
let dataCat = !!showAirport ? 'airport' : 'state';
let ftrLayers = {'state': null, 'airport': null};
let ftrGeo = {'state': null, 'airport': null};
let panelOpen = false;
let bh = {};
let placeholder = {
state: 'Search by state name/abbreviation',
airport: 'Search by airport name or FAA identifier'
}
const ta = $('.typeahead');
// Create map
const mapBounds = L.latLngBounds(L.latLng(50, -61), L.latLng(19, -127));
const map = L.map('map-container', {renderer: L.canvas(), preferCanvas: true})
.setView([39.8283, -98.5795], 4)
.setMaxBounds(mapBounds)
.fitBounds(mapBounds);
// Add attribution
map.attributionControl.addAttribution('Map created by <A HREF="https://www.indecon.com/" TARGET="_blank">Industrial Economics Incorporated</A>');
map.attributionControl.addAttribution('Powered by <A HREF="http://esri.maps.arcgis.com/home/index.html" TARGET="_blank">Esri</A>');
// Add the base layer
L.tileLayer('https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/{id}/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tile Layer by <A HREF="http://esri.maps.arcgis.com/home/index.html" TARGET="_blank">Esri</A>',
minZoom: 2,
maxZoom: 7,
id: 'World_Light_Gray_Base'
}).addTo(map);
// Figure out the data color ranges
_setChromaRanges();
// Create the states feature group layer
$.getJSON('data/cb_2023_states.json', function(data) {
ftrGeo['state'] = topojson.feature(data, data.objects.cb_2023_states);
ftrLayers['state'] = L.geoJson(ftrGeo['state'], {
style: _ftrStyle,
onEachFeature: function(feature, layer) {
layer.on({
mouseover: _highlightFeature,
mouseout: _resetHighlight,
click: _selectFeatureFromMap
});
layer.bindTooltip(feature.properties['NAME']);
}
});
const states = ftrGeo['state'].features.map(
function(o) {
const props = o.properties;
return {
id: props['STATEFP'],
text: props['NAME'] + ' ' + props['STUSPS'],
label: props['NAME'] + ' (' + props['STUSPS'] + ')',
ftr: o
};
}
);
bh['state'] = new Bloodhound({
local: states,
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
identify: function(obj) { return obj.id; },
sorter: function(a,b){
return a.label.toUpperCase() < b.label.toUpperCase() ? -1 : 1;
}
});
_completeInit();
});
// Create the airport feature group layer
$.getJSON('data/FAA_Top_200_Airports.json', function(data) {
ftrGeo['airport'] = topojson.feature(data, data.objects.FAA_Top_200_Airports);
ftrLayers['airport'] = L.geoJson(ftrGeo['airport'], {
style: _ftrStyle,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, styles['airport']);
},
onEachFeature: function(feature, layer) {
layer.on({
mouseover: _highlightFeature,
mouseout: _resetHighlight,
click: _selectFeatureFromMap
});
layer.bindTooltip(feature.properties['NAME'] + ' (' + feature.properties['LOC_ID'] + ')');
}
});
const airports = ftrGeo['airport'].features.map(
function(o) {
const props = o.properties;
return {
id: props['UNIQUE_ID'],
text: props['NAME'] + ' ' + props['LOC_ID'],
label: props['NAME'] + ' (' + props['LOC_ID'] + ')',
ftr: o
};
}
);
bh['airport'] = new Bloodhound({
local: airports,
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
identify: function(obj) { return obj.id; },
sorter: function(a,b){
return a.label.toUpperCase() < b.label.toUpperCase() ? -1 : 1;
}
});
_updateLegend();
_completeInit();
});
// Build the slide reveal
const infoPanel = $("#info-panel").slideReveal({
trigger: $("#trigger"),
push: false,
position: "right",
width: 325,
speed: 250,
hide: function(p, o) { p.removeClass('panel-shadow'); },
hidden: _closePanel,
show: function(p, o) { p.addClass('panel-shadow'); },
shown: function() { panelOpen = true;}
});
$('#info-panel .close-button').on('click', function(){$('#info-panel').slideReveal('hide');})
// $('#layer-switch').on('click', (e) => {
// _activateLayer(true);
// $(e.currentTarget).toggleClass('airport', dataCat !== 'airport');
// });
$('#tt-clear').on('click', _clearTypeahead);
// Set resize event for window
window.addEventListener('resize', (event) => {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
map.fitBounds(mapBounds, {animate: false});
timeoutId = null;
}, 50);
}, true);
function _completeInit() {
if (!!ftrLayers['airport'] && !!ftrLayers['state']) {
_activateLayer();
_initTypeahead();
}
}
function _activateLayer(toggle) {
if (!!toggle) {
if (panelOpen) {
$('#info-panel').slideReveal('hide');
}
map.flyToBounds(mapBounds);
// Remove the old feature group layer
ftrLayers[dataCat].remove();
dataCat = dataCat === 'state' ? 'airport' : 'state';
// Recalculate the data color ranges
_updateFtrColors();
// Reinit the typeahead
_clearTypeahead();
ta.typeahead('destroy');
_initTypeahead();
}
// Activate the feature layer
ftrLayers[dataCat].addTo(map);
}
function _setChromaRanges() {
const data = iecData[dataCat][dataId];
const option = data_config.find(function(o){return o.ref_id === dataId});
let vals = [];
let ranges = [];
for (key in data) {
vals.push(data[key]);
}
vals.sort(function(a, b){return a - b});
// Let chroma take a first pass at our numbers and break them into ranges
ranges = chroma.limits(vals, 'q', scale_color_count);
colorFn = chroma.scale(option.chroma_scale).padding([.2, 0]).classes(ranges);
_updateLegend();
}
function _updateLegend() {
const div = $('.map-ctrl.legend')[0];
div.innerHTML = '';
const scale = colorFn.classes();
const option = data_config.find(function(o){return o.ref_id === dataId});
let txt, lowval, highval;
for (let x = 0, y = scale.length - 1; x<y; x++) {
lowval = x === 0 ? '' : __formatVal(scale[x]);
highval = x === y - 1 ? '' : __formatVal(scale[x + 1]);
txt = lowval == '' ? '<= ' + highval : (highval == '' ? lowval + ' +' : lowval + ' – ' + highval);
div.innerHTML += '<div><i style="background-color:' + colorFn(scale[x]) + '"></i> ' + txt + '</div>';
}
if (!$select) _buildSelect();
$(div).prepend($select);
$(div).append('<div class="iec-footnote">IEc (2050) report values</div>');
function __formatVal(val) {
return (option.currency ? '$' : '') + val.toLocaleString('en-US', {minimumFractionDigits: 0,
maximumFractionDigits: option.decimal_places});
}
};
function _ftrStyle(feature) {
return Object.assign({}, styles[dataCat],{fillColor: _getColor(feature.properties.UNIQUE_ID || feature.properties.STUSPS)});
}
function _getColor(id) {
const data = iecData[dataCat][dataId];
return colorFn(data[id]).hex();
}
function _highlightFeature(e) {
const fg = e.target;
fg.setStyle(styles['highlight']);
fg.bringToFront();
}
function _resetHighlight(e) {
ftrLayers[dataCat].resetStyle();
if (dataCat === 'state' && !!layerSel?.bringToFront) {
layerSel.bringToFront();
}
}
function _selectFeatureFromMap(e) {
_selectFeature(e.target.feature);
}
function _selectFeature(ftr) {
selectedFtr = ftr;
const id = ftr.properties.UNIQUE_ID || ftr.properties.STUSPS;
// Remove the previous selected layer if one exists
if (!!layerSel) layerSel.remove();
// Now create a new layer from the geometry
layerSel = L.GeoJSON.geometryToLayer(ftr.geometry);
if (dataCat === 'state') {
layerSel.setStyle(Object.assign({}, styles['selected'], {fillColor: _getColor(id)}));
layerSel.addTo(map);
// Bring it to the front so it stays visible
layerSel.bringToFront();
} else {
// This has to happen for the marker to appear on the map
layerSel.addTo(map);
}
// Now open the side panel
_displayInfoPanel();
}
function _buildSelect() {
$select = $('<select id="dataset-sel"></select>');
data_config.forEach(
function(o) {
$select.append('<OPTION value="' + o.ref_id + '">' + o.name);
}
);
$select.on('change', function() {
dataId = this.value;
_updateFtrColors();
// If we have a selected state, then we need to update its color and bring it to the front
if (!!selectedFtr && !!selectedFtr.properties['STUSPS']) {
const id = selectedFtr.properties['STUSPS'];
layerSel.setStyle(Object.assign({}, styles['selected'], {fillColor: _getColor(id)}));
layerSel.bringToFront();
}
});
}
function _updateFtrColors() {
_setChromaRanges();
ftrLayers[dataCat].clearLayers();
ftrLayers[dataCat].addData(ftrGeo[dataCat]);
};
function _initTypeahead() {
ta.typeahead({
hint: true,
highlight: true,
minLength: 2
}, {
display: 'label',
source: bh[dataCat],
async: true,
limit: Infinity
}).bind('typeahead:select', function(ev, suggestion) {
_selectFeature(suggestion.ftr);
// Remove focus from the input field or ESC won't close the info panel
$('.tt-input').blur();
});
ta.attr('placeholder', placeholder[dataCat]);
}
function _clearTypeahead() {
ta.typeahead('val', '');
}
function _closePanel() {
panelOpen = false;
// Remove the selected layer
layerSel.remove();
layerSel = null;
selectedFtr = null;
}
function _displayInfoPanel() {
const id = selectedFtr.properties.UNIQUE_ID || selectedFtr.properties.STUSPS;
const title = (dataCat === 'state' ? 'State of ' : '') + selectedFtr.properties['NAME'];
$('.data-container .header').text(title);
data_config.forEach(function(o){
$('.data-' + o.ref_id).text(map.name);
const tmp = iecData[dataCat][o.ref_id];
const val = (o.currency ? '$' : '') + tmp[id].toLocaleString('en-US', {minimumFractionDigits: 0,
maximumFractionDigits: o.decimal_places});
$('.data-' + o.ref_id).text(val);
});
// Open the side panel
if(! panelOpen) {
infoPanel.slideReveal('show');
}
}
})();