-
Notifications
You must be signed in to change notification settings - Fork 0
/
heatmap.mjs
1304 lines (1140 loc) · 50.3 KB
/
heatmap.mjs
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
import { loadModules, setDefaultOptions } from 'https://unpkg.com/esri-loader/dist/esm/esri-loader.js';
(async () => {
setDefaultOptions({
css: true,
// url: 'http://localhost:8000/buildOutput/init.js',
url: 'https://jscore.esri.com/debug/4.16/dojo/dojo.js',
// version: 'next',
});
const [
Map,
MapView,
FeatureLayer,
generateHistogram,
HistogramRangeSlider,
Histogram,
uniqueValues,
Legend,
Renderer,
colorRamps,
Color,
viewColorUtils,
FeatureFilter,
] = await loadModules([
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer",
"esri/smartMapping/statistics/histogram",
"esri/widgets/HistogramRangeSlider",
"esri/widgets/Histogram",
"esri/smartMapping/statistics/uniqueValues",
"esri/widgets/Legend",
"esri/renderers/Renderer",
"esri/smartMapping/symbology/support/colorRamps",
"esri/smartMapping/symbology/color",
"esri/views/support/colorUtils",
"esri/views/layers/support/FeatureFilter",
]);
// data urls
var datasets = {
'Citclops Water': "8581a7460e144ae09ad25d47f8e82af8_0",
'Tucson Demographics': "35fda63efad14a7b8c2a0a68d77020b7_0",
'Seattle Bike Facilities': "f4f509fa13504fb7957cef168fad74f0_1",
'Traffic Circles': "717b10434d4945658355eba78b66971a_6",
'Black Cat Range': "28b0a8a0727d4cc5a2b9703cf6ca4425_0",
'King County Photos': "383878300c4c4f8c940272ba5bfcce34_1036",
'NYC bags': "7264acdf886941199f7c01648ba04e6b_0",
}
let widgetsDiv = document.getElementById('widgetsDiv');
let filterResults = document.getElementById('filterResults');
// dataset switcher
var datasetList = document.getElementById('datasetList');
// populate dropdown with all attributes
for (let [key, value] of Object.entries(datasets)) {
// create new option element and add it to the dropdown
var opt = document.createElement('option');
opt.text = key;
opt.value = value;
datasetList.appendChild(opt);
}
datasetList.addEventListener('change', async event => {
({ layer, dataset } = await loadDataset({ datasetId: event.target.value, env: 'prod' }));
});
// track widgets and state
var timeSlider = null;
var dataset = null;
var layer = null;
var view = null;
var layerView = null;
var widgets = [];
// var zoomToDataCheckbox;
var attributeList;
// URL params
const params = new URLSearchParams(window.location.search);
var env = 'prod';
if (Array.from(params).length != 0) {
var datasetId = params.get('dataset');
const datasetSlug = params.get('slug');
({ layer, dataset } = await loadDataset({ datasetId: datasetId, datasetSlug: datasetSlug, env: env }));
env = params.get('env');
} else {
var datasetId = datasetList.options[datasetList.selectedIndex].value;
({ layer, dataset } = await loadDataset({ datasetId: datasetId, env: env }));
}
async function switchSelected (event, fieldName = null) {
fieldName = fieldName ? fieldName : event.currentTarget.dataset.field;
const field = getDatasetField(dataset, fieldName);
// guess at a style for this field
try {
// initialize a new layer
layer = new FeatureLayer({
// renderer: {type: 'simple'},
renderer: {type: 'heatmap'},
url: dataset.attributes.url
});
switchStyles(null, layer, fieldName);
} catch(e) {
console.log('e:', e)
}
}
async function addFilter(event = null, fieldName = null, fieldStats = null) {
let target = event ? event.currentTarget : document.getElementById(fieldName);
fieldName = fieldName ? fieldName : target.dataset.field;
const field = getDatasetField(dataset, fieldName);
let firstFilter = document.getElementById('firstfilter');
firstFilter ? firstFilter.remove() : null;
let filter = document.createElement('div');
filter.classList.add('filterDiv');
fieldStats = fieldStats ? fieldStats : field.statistics;
filter.innerHTML = generateLabel(field, fieldStats);
// actions
let icons = document.createElement('span');
icons.innerHTML = " 🅧 ";
icons.onclick = removeFilter;
icons.classList.add('filterIcons');
let tooltip = document.createElement('span');
tooltip.classList.add('tooltip')
tooltip.innerText = "Delete filter";
filter.appendChild(icons);
icons.insertBefore(tooltip, icons.firstChild)
let filtersList = document.getElementById('filtersList');
filtersList.appendChild(filter);
document.getElementById('filtersCount').innerHTML = `Applying ${filtersList.children.length} filters`;
let container = document.createElement('div');
filter.appendChild(container);
if (!view) {
view = await drawMap(layer, dataset)
}
layerView = await view.whenLayerView(layer);
const { categorical, pseudoCategorical } = await datasetFieldCategorical(dataset, fieldName, layer);
const numberLike = await datasetFieldIsNumberLike(dataset, fieldName, layer);
// (pseudo-)categorical - most records are covered by a limited # of unique values
// or all other string values
if (pseudoCategorical || (field.simpleType === 'string' && !numberLike)) {
// value list
widget = await makeStringWidget({ dataset, fieldName, layer, layerView, container, slider: true });
}
// numerics and dates
else {
var widget = await makeHistogramWidget({ dataset, fieldName, layer, layerView, container, slider: true });
container.classList.add('histogramWidget');
// set whereClause attribute
let whereClause = widget.generateWhereClause(fieldName);
// whereClause = whereClause.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
widget.container.setAttribute('whereClause', whereClause);
}
// if (field.simpleType === 'date') {
// // Time slider
// widget = await makeTimeSliderWidget({ dataset, fieldName, layer, layerView, slider: true });
// }
let sidebar = document.getElementById('sidebar')
sidebar.scrollTop = sidebar.scrollHeight;
widget.container.setAttribute('fieldName', fieldName);
widget.container.setAttribute('numberLike', numberLike);
}
// create a histogram
async function makeHistogram ({dataset, fieldName, layer, layerView, container, slider = false, where = null, features = null }) {
// wrap in another container to handle height without fighting w/JSAPI and rest of sidebar
const parentContainer = container;
let newcontainer = document.createElement('div');
parentContainer.appendChild(newcontainer);
try {
let params = {
layer: layer,
field: fieldName,
numBins: 30,
where,
features // optional existing set of features
};
let values, bins, source, coverage;
try {
values = await generateHistogram(params);
source = 'widgets';
coverage = 1;
} catch(e) {
try {
// histogram generation failed with automated server call, try using features from server query
console.log('histogram generation failed with automated server call, try using features from server query', e);
// params.features = (await layer.queryFeatures()).features;
// const featureCount = await layer.queryFeatureCount();
// if (params.features.length != featureCount) throw new Error('params.features.length != featureCount');
const { features, exceededTransferLimit } = await layer.queryFeatures();
if (exceededTransferLimit) throw new Error('exceeded server limit querying features');
params.features = features;
values = await generateHistogram(params);
source = 'layerQuery';
// coverage = params.features.length / featureCount;
} catch(e) {
// histogram generation failed with automated server call, try using features from server query
console.log('histogram generation failed with automated server call, try reconstructing from unique values', e);
try {
let uniqueValues = (await getDatasetFieldUniqueValues(dataset, fieldName, layer)).values;
let domain = [Math.min(...uniqueValues.map(a => a.value)),
Math.max(...uniqueValues.map(a => a.value))]
// remove nulls
var filtered = uniqueValues.filter(a => a.value != null);
// manually reconstruct a feature values array from the unique values and their counts -
// normalize array length to 1000, as precision isn't as important as speed here
const divisor = dataset.attributes.recordCount / 1000;
let arr = [];
for (let x = 0; x < filtered.length; x++) {
for (let y = 0; y < Math.ceil(filtered[x].count/divisor); y++) {
arr.push(filtered[x].value);
};
}
// use d3 to bin histograms
let d3bins = d3.histogram() // create layout object
.domain([Math.min(...filtered.map(a => a.value)),
Math.max(...filtered.map(a => a.value))]) // to cover range
.thresholds(29) // separated into 30 bins
(arr); // pass the array
// convert the d3 bins array to a bins object
bins = [];
for (let x = 0; x < d3bins.length; x++) {
bins.push({
minValue: d3bins[x]['x0'],
maxValue: d3bins[x]['x1'],
count: d3bins[x].length,
});
}
// put the bins in the params object
values = {
'bins': bins,
'minValue': Math.min(...filtered.map(a => a.value)),
'maxValue': Math.max(...filtered.map(a => a.value)),
}
const featureCount = arr.length;
source = 'layerQuery';
coverage = 1;
} catch(e) {
// histogram generation failed with unique values, try using features in layer view
console.log('histogram generation failed with unique values, try using features in layer view', e);
params.features = (await layerView.queryFeatures()).features;
// const featureCount = await layer.queryFeatureCount();
values = await generateHistogram(params);
source = 'layerView';
// coverage = params.features.length / featureCount;
}
}
}
// Determine if field is an integer
const field = getDatasetField(dataset, fieldName);
const integer = await datasetFieldIsInteger(dataset, fieldName, layer);
const widget =
slider ?
// Histogram range slider widget
new HistogramRangeSlider({
bins: values.bins,
min: values.minValue,
max: values.maxValue,
values: [values.minValue, values.maxValue],
precision: integer ? 0 : 2,
container: container,
excludedBarColor: "#dddddd",
rangeType: "between",
labelFormatFunction: (value, type) => {
// apply date formatting to histogram
if (field.simpleType == 'date') {
return formatDate(value);
}
return value;
}
})
:
// plain histogram, for miniHistogram nested in timeSlider
new Histogram({
bins: values.bins,
min: values.minValue,
max: values.maxValue,
container: container,
rangeType: "between",
})
;
return { widget, values, source, coverage };
}
catch(e) {
console.log('histogram generation failed', e);
return {};
}
}
// make and place a histogram
async function makeHistogramWidget({ dataset, fieldName, layer, layerView, container = null, slider = true }) {
const wrapper = document.createElement('div');
wrapper.classList.add('histogramWidget');
container = container ? container : document.getElementById('filters');
container.appendChild(wrapper);
// filter by existing widgets on creation?
let features;
if (widgets.length > 0) {
const where = concatWheres({ server: true });
// query layer for all features in the other layers, filtered by the state of current layer
features = (await layer.queryFeatures( { where, outFields: [fieldName] })).features;
}
const histogram = await makeHistogram({ dataset, fieldName, layer, layerView, features, container: wrapper, slider: true });
if (histogram.widget) {
wrapper.widget = histogram.widget;
// set event handler to update map filter and histograms when handles are dragged
histogram.widget.on(["thumb-change", "thumb-drag", "segment-drag"], event => {
updateLayerView(layerView, fieldName, histogram.widget);
updateWidgets(layerView, fieldName, histogram.widget);
});
// register widget
widgets.push(histogram.widget);
}
return histogram.widget;
}
// make and place a value list of checkboxes
async function makeStringWidget({ dataset, fieldName, layer, container = null, slider = true }) {
// const listContainer = document.createElement('div');
// const listContainer = document.createElement('div');
container.classList.add('valueListWidget');
const field = getDatasetField(dataset, fieldName);
// Build filter/where clause and update layer
const onCheckboxChange = ({ checkboxes, layerView }) => {
let checked = checkboxes.filter(c => c.checked).map(c => JSON.parse(c.value));
let whereClause = '1=1';
if (checked.length > 0) {
const hasNull = checked.find(c => c.value == null) ? true : false;
checked = checked.filter(c => c.value != null);
let whereVals;
if (field.simpleType === 'date') {
whereVals = checked.map(c => +new Date(c.value));
whereClause = whereVals.map(v => `${fieldName} = ${v}`).join(' OR ');
} else {
whereVals = checked.map(c => {
if (typeof c.value === 'string') {
return `'${c.value}'`
} else {
return c.value;
}
});
whereClause = `${fieldName} IN (${whereVals.join(', ')})`;
}
if (hasNull) {
whereClause = whereVals ? `${whereClause} OR ` : '';
whereClause = `${fieldName} IS NULL`; // need special SQL handling for null vales
}
}
container.setAttribute('whereClause', whereClause);
const where = concatWheres({ server: false });
updateLayerViewEffect({ where });
};
const { fieldStats } = await createValueList({ dataset, fieldName, layer, container, onUpdateValues: onCheckboxChange });
fieldStats.container = container;
// register widget
widgets.push(fieldStats)
return fieldStats;
}
async function createValueList ({ dataset, fieldName, layer, container, onUpdateValues }) {
// <label>
// <calcite-checkbox checked="true"></calcite-checkbox> Switch is on
// </label>
container.classList.add('filter');
const list = document.createElement('div');
const header = document.createElement('div');
// header.innerText = 'Values';
header.classList.add('sidebarItemHeader');
list.appendChild(header);
const checkboxList = document.createElement('div');
list.appendChild(checkboxList);
const field = getDatasetField(dataset, fieldName);
const stats = await getDatasetFieldUniqueValues(dataset, fieldName, layer);
// if (!stats.topValues || stats.topValues.length === 0) {
// return {};
// }
let checkboxListenerDisabled = false;
function addValueListCheckbox (value, checkboxes) {
const checkbox = document.createElement('calcite-checkbox');
checkbox.value = JSON.stringify(value);
// const labelText = document.createTextNode(`${value.value} (${(value.pct * 100).toFixed(2)}% of records)`);
const labelText = document.createElement('span');
// handle null-ish, date, and other field formatting
if (value.value == null || (typeof value.value === 'string' && value.value.trim() === '')) {
labelText.innerHTML = '<span style="color: gray">No value</span>';
} else if (field.simpleType === 'date') {
labelText.innerHTML = formatDate(value.value);
} else {
labelText.innerHTML = value.value;
}
const labelSubText = document.createElement('span');
labelSubText.classList.add('subText');
labelSubText.innerText = value.pct != null ? `${(value.pct * 100).toFixed(2)}%` : '';
const onlyLink = document.createElement('a');
onlyLink.classList.add('valueListSideLink');
onlyLink.href = '#';
onlyLink.innerText = 'only';
const label = document.createElement('label');
label.classList.add('valueListCheckbox');
label.appendChild(checkbox);
label.appendChild(labelText);
label.appendChild(labelSubText);
label.appendChild(onlyLink);
checkbox.addEventListener('calciteCheckboxChange', (event) => {
if (!checkboxListenerDisabled) {
onUpdateValues({ checkboxes, event });
}
});
onlyLink.addEventListener('click', event => {
// disable change listener to keep it from firing as all checkboxes are updated
checkboxListenerDisabled = true;
// check selected box and un-check all others
checkboxes.forEach(c => {
c.checked = c === checkbox ? true : false;
});
// re-enable listener and invoke update handler just once
checkboxListenerDisabled = false;
onUpdateValues({ checkboxes, event });
});
checkboxList.appendChild(label);
return checkbox;
}
// clear all link
const clearLink = document.createElement('a');
clearLink.classList.add('valueListSideLink');
clearLink.href = '#';
clearLink.innerText = 'clear';
header.appendChild(clearLink);
clearLink.addEventListener('click', event => {
// disable change listener to keep it from firing as all checkboxes are updated
checkboxListenerDisabled = true;
// un-check all checkboxes
checkboxes.forEach(c => c.checked = false);
// re-enable listener and invoke update handler just once
checkboxListenerDisabled = false;
onUpdateValues({ checkboxes, event });
});
const checkboxes = [];
checkboxes.push(...stats.topValues.map(value => addValueListCheckbox(value, checkboxes)));
container.appendChild(list);
// search box
if (stats.uniqueCount > stats.topValues.length) {
const searchBox = document.createElement('input');
searchBox.classList.add('valueListSearchBox');
searchBox.type = 'text';
searchBox.placeholder = `Search ${stats.uniqueCount} ${fieldName} values...`;
const wrapper = document.createElement('div');
wrapper.classList.add('valueListSearchBoxWrapper');
list.appendChild(searchBox);
function searchSource(params) {
return async function doSearch(query, callback) {
const where = field.simpleType === 'date' ?
`CAST(${fieldName} AS VARCHAR(256)) LIKE lower('%${query}%')` : // convert dates to strings
`lower(${fieldName}) LIKE lower('%${query}%')`
const { features } = await layer.queryFeatures({
// where: `lower(${fieldName}) LIKE lower('%${query}%')`,
// where: `CAST(${fieldName} AS VARCHAR(256)) LIKE lower('%${query}%')`,
where,
orderByFields: [fieldName],
outFields: [fieldName],
returnDistinctValues: true,
num: 10
});
// de-dupe results (by turning into set)
const vals = new Set(features
.map(f => f.attributes[fieldName])
.map(v => typeof v === 'string' ? v.trim() : v)
.filter(value => {
// exclude any results already selected in checkboxes
return !checkboxes
.filter(c => c.checked)
.map(c => JSON.parse(c.value))
.map(v => v.value)
.includes(value);
})
);
// return values
callback([...vals].map(value => ({
value,
label: field.simpleType === 'date' ? formatDate(value) : value
})));
};
}
autocomplete(searchBox, { hint: false, clearOnSelected: false, }, [{
source: searchSource({ hitsPerPage: 5 }),
displayKey: 'label',
templates: {
suggestion: function(suggestion) {
return suggestion.label;
}
}
}]).on('autocomplete:selected', function(event, suggestion, dataset, context) {
let checkbox = checkboxes
.filter(c => !c.checked)
.find(c => JSON.parse(c.value).value === suggestion.value);
if (!checkbox) {
checkbox = addValueListCheckbox(suggestion, checkboxes);
checkboxes.push(checkbox);
}
checkbox.checked = true;
// TODO: why is this necessary? calcite event listener doesn't fire when checkbox added and set to checked in this flow
onUpdateValues({ checkboxes });
});
}
return { checkboxes, fieldStats: stats };
}
// update layerview filter based on widget, throttled
const updateLayerView = _.throttle(
async (layerView, fieldName, widget, value = null) => {
let whereClause;
if (widget.label === "Histogram Range Slider") {
whereClause = widget.generateWhereClause(fieldName);
// whereClause = whereClause.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
if (widget.label === "TimeSlider") {
// instead of unix timestamps, use SQL date formatting, as expected by layer.queryFeatures()
whereClause = `${fieldName} BETWEEN DATE ${formatSQLDate(value.start)} AND DATE ${formatSQLDate(value.end)}`;
}
// set whereClause attribute
widget.container.setAttribute('whereClause', whereClause);
const where = concatWheres({ server: false });
await updateLayerViewEffect({ where: where });
},
100,
{trailing: false}
);
// update the bins of all histograms except the current widget, throttled
const updateWidgets = _.throttle(
async (layerView, fieldName, currentWidget) => {
let widgets = Array.from(listWidgetElements());
// if there's only one widget, skip this
if (widgets.length === 1) return
// collect other widgets' fieldNames, skipping the current widget (handles nested widgets too)
let otherWidgets = widgets.filter(w => w.getAttribute('fieldname') != fieldName);
let fieldNames = otherWidgets.map(w => w.getAttribute('fieldname'));
// convert to a set to remove any duplicates (nested widgets), then back to array
fieldNames = [...new Set(fieldNames)];
let whereClause = currentWidget.container.getAttribute('whereClause');
const numberLike = currentWidget.container.getAttribute('numberLike') === "true";
if (numberLike) {
whereClause = whereClause.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
try {
// query layer for all features in the other layers, filtered by the state of current layer
let { features } = await layer.queryFeatures( { where: whereClause, outFields: fieldNames });
// update other widgets, passing in the filtered feature set
throttledUpdateOthers(otherWidgets, features);
} catch(e) {
throw new Error('Tried to update other widgets: '+e)
}
},
100,
{trailing: false}
);
// update the bins of a histogram
async function updateHistogram(widget, fieldName, features, { numberLike } = {}) {
let values;
if (features) {
let valueExpression;
let sqlExpression;
if (numberLike) {
// copy features and cast string field to number
// features = features.map(f => {
// const clone = f.clone();
// const value = Number(clone.getAttribute(fieldName));
// clone.setAttribute(fieldName, value);
// // clone.sourceLayer = null;
// return clone;
// });
valueExpression = `Number($feature.${fieldName})`;
sqlExpression = `CAST(${fieldName} AS FLOAT})`;
}
let params = {
layer,
view: layerView.view,
features,
field: valueExpression ? null : fieldName,
valueExpression,
// field: fieldName,
// sqlExpression,
numBins: 30,
// minValue: widget.min,
// maxValue: widget.max,
// values: [widget.values[0], widget.values[1]]
// values: [widget.min, widget.max]
// sqlWhere: concatWheres()
// sqlWhere: where
};
try {
values = await generateHistogram(params);
if (values.bins) {
widget.bins = values.bins;
}
} catch(e) {
console.log('e:', e)
}
}
}
function updateOthers(otherWidgets, features) {
for (const widget of otherWidgets) {
// can't update TimeSliders
if (widget.label == "TimeSlider") continue;
const numberLike = widget.getAttribute('numberLike') === "true";
updateHistogram(widget.widget, widget.getAttribute('fieldName'), features, { numberLike });
}
}
const throttledUpdateOthers = _.throttle(updateOthers, 100, {trailing: false});
// list all known widget DOM elements
function listWidgetElements() {
return [...document.getElementById('filtersList').querySelectorAll('[whereClause]')];
}
// concatenate all the where clauses from all the widgets
function concatWheres( { server }) {
let whereClause = '';
let widgets = listWidgetElements();
// generate master here clause with simple string concatenation
for (const [x, widget] of widgets.entries()) {
if (x > 0) whereClause += ' AND ';
let widgetWhere = widget.getAttribute('whereClause');
// explicit cast for number-likes, for feature layer (server-side) queries ONLY
// skip for feature layer view (client-side) queries, which work *without* the cast (but fail with it)
const numberLike = widget.getAttribute('numberLike') === "true";
if (server && numberLike) {
const fieldName = widget.getAttribute('fieldName');
widgetWhere = widgetWhere.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
whereClause += '(' + widgetWhere + ')';
// whereClause += '(' + widget.getAttribute('whereClause') + ')';
}
return whereClause;
}
// update the map view with a new where clause
async function removeFilter(event, fieldName = null) {
fieldName = fieldName ? fieldName : event.currentTarget.dataset.field;
let filter = event.currentTarget.parentElement;
let filtersList = filter.parentElement;
filter.remove();
document.getElementById('filtersCount').innerHTML = `Applying ${filtersList.children.length} filters`;
}
async function switchAttribute(event, fieldName = null) {
fieldName = fieldName ? fieldName : event.currentTarget.dataset.field;
const field = getDatasetField(dataset, fieldName);
document.querySelector('#attributeListButton').innerHTML = fieldName;
switchStyles(null, layer, fieldName);
}
async function switchStyles(view, layer, fieldName) {
var field;
try {
if (!view) {
view = await drawMap(layer, dataset)
}
widgets.innerText += '\nDrawing '+fieldName+'.';
layerView = await view.whenLayerView(layer);
} catch(e) {
console.error(new Error(e));
layerView = await view.whenLayerView(layer);
}
var {renderer} = await autoStyle(null, fieldName, dataset, layer, true);
field = getDatasetField(dataset, fieldName);
layer.renderer = renderer;
layer.minScale = 0; // draw at all scales
layer.outFields = ["*"]; // get all fields (easier for prototyping, optimize by managing for necessary fields)
// clear previous filters
if (typeof layerView != 'undefined') {
updateLayerViewEffect({ updateExtent: true });
}
// wait for renderer to finish
var watcher = await layerView.watch("updating", value => {
console.log('?updated')
if (renderer) {
console.log('?renderer')
layerView.queryFeatureCount({
where: '1=1',
outSpatialReference: layerView.view.spatialReference
}).then(count => {
console.log('count?', count)
let featuresCount = document.getElementById('featuresCount');
featuresCount.innerText = count;
let filterResults = document.getElementById('filterResults');
// filterResults.innerText = 'Showing '+count+' '+field.simpleType+' features.';
cleanup();
});
} else {
console.log('no renderer yet')
}
});
// remove watcher as soon as it finishes
function cleanup() {
watcher.remove()
}
};
async function drawMap(layer, dataset) {
const map = new Map({
basemap: "gray-vector",
layers: layer,
});
view = new MapView({
container: "viewDiv",
map: map,
extent: getDatasetExtent(dataset),
ui: { components: [] }
});
layerView = await view.whenLayerView(layer).then((layerView) => {
// var legend = await new Legend({
// view: view,
// layerInfos: [{
// layer: layer,
// title: "Legend"
// }]
// });
// view.ui.add(legend, "bottom-right");
});
view.ui.add('zoomToData', 'bottom-right');
const zoomToDataCheckbox = document.querySelector('#zoomToData calcite-checkbox');
zoomToDataCheckbox.addEventListener('calciteCheckboxChange', () => {
updateLayerViewEffect({ updateExtent: zoomToDataCheckbox.checked });
});
// put vars on window for debugging
Object.assign(window, { view, map, dataset, layer, layerView, getDatasetField, getDatasetFieldUniqueValues, /*histogram, histogramValues,*/ generateHistogram, HistogramRangeSlider, uniqueValues });
// Dataset info
document.querySelector('#datasetName').innerHTML = dataset.attributes.name;
document.querySelector('#orgName').innerHTML = dataset.attributes.orgName || '';
document.querySelector('#recordCount').innerHTML = `${dataset.attributes.recordCount} records`;
return view;
}
// update layerview filter based on histogram widget, throttled
const updateLayerViewWithHistogram = _.throttle(
async (layerView, fieldName, where) => {
await updateLayerViewEffect({ where });
},
50
);
async function loadDataset (args) {
const datasetURL = `https://opendata${args.env === 'qa' ? 'qa' : ''}.arcgis.com/api/v3/datasets/${args.datasetId}`;
try {
dataset = (await fetch(datasetURL).then(r => r.json())).data;
} catch(e) { console.log('failed to load dataset', e); }
attributeList = updateAttributeList(dataset, '#attributeList', () => { addFilter(event) });
updateAttributeList(dataset, '#styleListItems', async () => {var { renderer } = await autoStyle(event, null, dataset, null); layer.renderer = renderer})
let fieldName = Object.keys(dataset.attributes.statistics.numeric)[0]
let field = getDatasetField(dataset, fieldName)
switchSelected(null, field.name);
return { dataset, layer };
}
// analyze a dataset and choose an initial best-guess symbology for it
async function autoStyle(event = null, fieldName = null, dataset = null, layer = null, first = false) {
let target = event ? event.currentTarget : document.getElementById(fieldName);
fieldName = fieldName ? fieldName : target.getAttribute('data-field');
const field = getDatasetField(dataset, fieldName);
const geometryType = dataset.attributes.geometryType;
// debugger
let datasetStats = dataset.attributes.statistics[field.simpleType][fieldName.toLowerCase()].statistics;
let fieldStats = field.statistics;
let minValue = fieldStats.values.min;
let maxValue = fieldStats.values.max;
let symbol;
if (!!layer) {
var query = layer.createQuery();
// query.outFields = [fieldName]
try {
let uniqueValues = (await getDatasetFieldUniqueValues(dataset, fieldName, layer)).values;
// remove nulls
var filtered = uniqueValues.filter(a => a.value != null);
// manually reconstruct a feature values array from the unique values and their counts -
// normalize array length to 1000, as precision isn't as important as speed here
// const divisor = dataset.attributes.recordCount / 1000;
// use the whole set
const divisor = 1;
let arr = [];
for (let x = 0; x < filtered.length; x++) {
for (let y = 0; y < Math.ceil(filtered[x].count/divisor); y++) {
arr.push(filtered[x].value);
};
}
var numBins = (uniqueValues.length > 30 ? 30 : uniqueValues.length)
// use d3 to bin histograms
let d3bins = d3.histogram() // create layout object
.domain([Math.min(...filtered.map(a => a.value)),
Math.max(...filtered.map(a => a.value))]) // to cover range
.thresholds(numBins - 1) // separated into 30 bins
(arr); // pass the array
// convert the d3 bins array to a bins object
var bins = [];
for (let x = 0; x < d3bins.length; x++) {
bins.push({
minValue: d3bins[x]['x0'],
maxValue: d3bins[x]['x1'],
count: d3bins[x].length,
});
}
// put the bins in the params object
var values = {
'bins': bins,
'minValue': Math.min(...filtered.map(a => a.value)),
'maxValue': Math.max(...filtered.map(a => a.value)),
}
const featureCount = arr.length;
var source = 'layerQuery';
var coverage = 1;
} catch(e) {
// histogram generation failed with unique values, try using features in layer view
console.log('histogram generation failed with unique values, try using features in layer view:');
console.error(new Error(e));
if (typeof layerView != 'undefined') {
const { features } = await layerView.queryFeatures();
const featureCount = await layer.queryFeatureCount();
var values = await generateHistogram(params);
var source = 'layerView';
var coverage = params.features.length / featureCount;
} else {
console.warn('No layerView')
}
}
}
var opacity = .25;
if (geometryType === 'esriGeometryPoint') {
// scale point size based on viewport size, number of points, and "clumpiness" of the data,
// in order to reduce overlap of points
// if there's still a lot of points, adjust opacity to show points through each other
// pick a color scheme based on distribution of the data:
// if a linear distribution, choose a linear–
// if a log or exp distribution, choose log or exp –
// if a normal distribution or something similar, choose "extremes"
// choose colors based on background theme – dark on light, light on dark
symbol = {
type: "simple-marker",
outline: {
// makes the outlines of all features consistently light gray
color: "lightgray",
width: 0.05
},
size: '3px',
opacity: opacity,
}
}
// choose ramp
var num = 9;
if (!first) {
while (num == 9) {
num = Math.floor(Math.random() * 19)+1;
}
}
let thisramp = colorRamps.byName(`Heatmap ${num}`);
var rampColors = thisramp.colors;
// filterResults.innerText = 'Showing '+fieldStats.values.count+' '+field.simpleType+' values.';
var rMin = rampColors[0];
var rMid = rampColors[Math.floor((rampColors.length-1)/2)];
var rMax = rampColors[rampColors.length-1];
var renderer = {
type: "simple", // autocasts as new SimpleRenderer()
symbol: symbol,
visualVariables: [{
type: "color", // indicates this is a color visual variable
field: fieldName,
// normalizationField: "TOTPOP_CY", // total population
stops: [{
value: minValue,
color: {r: rMin.r, g: rMin.g, b: rMin.b, a: opacity},
label: minValue
},{
value: (maxValue+minValue)/2,
color: {r: rMid.r, g: rMid.g, b: rMid.b, a: opacity},
label: (maxValue+minValue)/2,
},{
value: maxValue,
color: {r: rMax.r, g: rMax.g, b: rMax.b, a: opacity},
label: maxValue
}]
}]
};
renderer = {
type: "heatmap", // autocasts as new HeatmapRenderer()
colorStops: [
{ color: "rgba(63, 40, 102, 0)", ratio: 0 },
{ color: "#ffff00", ratio: 1 }
],
maxPixelIntensity: 25,
minPixelIntensity: 0
};
return {renderer};
}
function getDatasetExtent (dataset) {
const extent = dataset.attributes.extent;