Repository navigation
Expand file tree
/
Copy pathsplit-test.html
More file actions
485 lines (399 loc) · 17 KB
/
Copy pathsplit-test.html
File metadata and controls
485 lines (399 loc) · 17 KB
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
<!--
This page is an experiment in auto-styling based on a selected attribute.
Sample dataset URL:
http://localhost:8080/widget-coordination.html?dataset=8581a7460e144ae09ad25d47f8e82af8_0
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<title>Filters</title>
<link href="widget-coordination.css" rel="stylesheet">
<script src="https://unpkg.com/lodash@4.17.15/lodash.js"></script>
<script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.min.js"></script>
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<!-- calcite components -->
<script
type="module"
src="https://unpkg.com/@esri/calcite-components@1.0.0-beta.24/dist/calcite/calcite.esm.js"
></script>
<link
rel="stylesheet"
type="text/css"
href="https://unpkg.com/@esri/calcite-components@1.0.0-beta.24/dist/calcite/calcite.css"
/>
<script type="module">
import { loadModules, setDefaultOptions } from 'https://unpkg.com/esri-loader/dist/esm/esri-loader.js';
import { makeTimeSliderWidget, makeHistogramWidget, updateLayerView, stopTimePlayback } from './widgets.js'
(async () => {
setDefaultOptions({
css: true,
// url: 'http://localhost:8000/buildOutput/init.js',
// version: 'next',
});
const [
Map,
MapView,
FeatureLayer,
generateHistogram,
Histogram,
HistogramRangeSlider,
TimeSlider,
uniqueValues,
webMercatorUtils
] = await loadModules([
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer",
"esri/renderers/smartMapping/statistics/histogram",
"esri/widgets/Histogram",
"esri/widgets/HistogramRangeSlider",
"esri/widgets/TimeSlider",
"esri/renderers/smartMapping/statistics/uniqueValues",
"esri/geometry/support/webMercatorUtils"
]);
// SCENE SETUP
//
// parse URL params
const params = new URLSearchParams(window.location.search);
const datasetId = params.get('dataset');
const datasetSlug = params.get('slug');
const env = params.get('env') || 'prod';
// load dataset
const { layer, dataset } = await loadDataset({ datasetId, datasetSlug, env });
// display dataset info
document.querySelector('#datasetName').innerHTML = dataset.attributes.name;
document.querySelector('#orgName').innerHTML = dataset.attributes.orgName || '';
document.querySelector('#recordCount').innerHTML = `${dataset.attributes.recordCount} records`;
// MAP SETUP
//
// load map and setup global variables
const map = new Map({
basemap: "dark-gray-vector",
layers: [layer]
});
const view = new MapView({
container: "viewDiv",
map: map,
extent: getDatasetExtent(dataset)
});
const layerView = await view.whenLayerView(layer);
const attributeList = updateAttributeList(dataset);
// put vars on window for debugging
Object.assign(window, { view, map, dataset, layer, layerView, getDatasetField, getDatasetFieldUniqueValues, /*histogram, histogramValues,*/ generateHistogram, HistogramRangeSlider, uniqueValues });
// DATA FUNCTIONS
//
// load a dataset
async function loadDataset ({ datasetId, datasetSlug, env }) {
let dataset = {};
if (datasetId) { // dataset id provided directly
// https://opendataqa.arcgis.com/api/v3/datasets/97a641ac39904f349fb5fc25b94207f6
const datasetURL = `https://opendata${env === 'qa' ? 'qa' : ''}.arcgis.com/api/v3/datasets/${datasetId}`;
try {
dataset = (await fetch(datasetURL).then(r => r.json())).data;
} catch(e) { console.log('failed to load dataset from id', datasetId, e); }
} else if (datasetSlug) { // dataset slug provided as alternate
// https://opendata.arcgis.com/api/v3/datasets?filter%5Bslug%5D=kingcounty%3A%3Aphoto-centers-for-2010-king-county-orthoimagery-project-ortho-image10-point
const filter = `${encodeURIComponent('filter[slug]')}=${encodeURIComponent(datasetSlug)}`
const datasetURL = `https://opendata${env === 'qa' ? 'qa' : ''}.arcgis.com/api/v3/datasets?${filter}`;
try {
dataset = (await fetch(datasetURL).then(r => r.json())).data[0];
} catch(e) { console.log('failed to load dataset from slug', datasetSlug, e); }
}
let symbol = {
type: 'simple-marker', size: '5px',
color: [51, 51, 204, 0.0],
outline: {
color: [256, 256, 256, 1],
width: 0.5
},
}
// if (geometryType === 'point') {
// symbol = { ...symbol, type: 'simple-marker', size: '8px' };
// }
// else if (geometryType === 'polyline') {
// symbol = { ...symbol, type: 'simple-line', width: '4px' };
// }
// else if (geometryType === 'polygon') {
// symbol = { ...symbol, type: 'simple-fill' };
// }
const layer = new FeatureLayer({
renderer: { type: 'simple', symbol },
url: dataset.attributes.url
});
layer.minScale = 0; // draw at all scales
layer.outFields = ["*"]; // get all fields (easier for prototyping, optimize by managing for necessary fields)
return { dataset, layer };
}
function getDatasetExtent (dataset) {
const extent = dataset.attributes.extent;
return {
xmin: extent.coordinates[0][0],
ymin: extent.coordinates[0][1],
xmax: extent.coordinates[1][0],
ymax: extent.coordinates[1][1],
spatialReference: extent.spatialReference
};
}
function getDatasetField (dataset, fieldName) {
fieldName = fieldName.toLowerCase();
const field = dataset.attributes.fields.find(f => f.name.toLowerCase() === fieldName);
const stats = [...Object.entries(dataset.attributes.statistics).values()].find(([, fields]) => fields[fieldName]);
// add "simple type" (numeric, date, string) and stats into rest of field definition
return {
...field,
simpleType: stats && stats[0],
statistics: stats && stats[1][fieldName].statistics
}
}
const DATASET_FIELD_UNIQUE_VALUES = {}; // cache by field name
async function getDatasetFieldUniqueValues (dataset, fieldName, layer) {
if (!DATASET_FIELD_UNIQUE_VALUES[fieldName]) {
const field = getDatasetField(dataset, fieldName);
let stats;
if (field.statistics && field.statistics.uniqueCount) {
stats = { ...field.statistics };
} else {
const uniqueValueInfos = (await uniqueValues({ layer, field: fieldName }))
.uniqueValueInfos
.sort((a, b) => a.count > b.count ? -1 : 1);
const count = uniqueValueInfos.reduce((count, f) => count + f.count, 0);
stats = {
count,
uniqueCount: uniqueValueInfos.length,
values: uniqueValueInfos
}
}
// add percent of records
stats.values = stats.values
// .filter(v => v.value != null && (typeof v.value !== 'string' || v.value.trim() !== ''))
.map(v => ({ ...v, pct: v.count / stats.count }));
// get top values
const maxTopValCount = 12;
// stats.topValues = stats.values.slice(0, maxTopValCount);
stats.topValues = [];
if (stats.uniqueCount < maxTopValCount) {
stats.topValues = stats.values;
} else {
let coverage = 0;
for (let i=0, coverage=0; i < stats.values.length; i++) {
// let stat = { ...stats.values[i], pct: stats.values[i].count / recordCount };
const stat = stats.values[i];
// if (coverage >= 0.80 && stat.pct < 0.05 && stats.topValues.length >= maxTopValCount) break;
if (stat.pct < 0.015 || stats.topValues.length >= maxTopValCount) break;
stats.topValues.push(stat);
coverage += stat.pct;
}
}
DATASET_FIELD_UNIQUE_VALUES[fieldName] = stats;
}
return DATASET_FIELD_UNIQUE_VALUES[fieldName];
}
// Add an entry to the attribute dropdown
function updateAttributeList (dataset) {
// create <calcite-dropdown-item> for each attribute
const attributeList = document.querySelector('#attributeList > calcite-dropdown-group');
const attributes = [
...Object.entries(dataset.attributes.statistics.numeric || {}),
...Object.entries(dataset.attributes.statistics.date || {}),
...Object.entries(dataset.attributes.statistics.string || {})
];
attributes
.map(([fieldName, { statistics: fieldStats }]) => [fieldName, fieldStats]) // grab stats
.filter(([fieldName, fieldStats]) => { // exclude fields with one value
return !fieldStats ||
!fieldStats.values ||
fieldStats.uniqueCount > 1 || // unique count reported as 0 for sampled data
fieldStats.values.min !== fieldStats.values.max
})
.forEach(([fieldName, fieldStats]) => {
// dataset.attributes.fieldNames
// .map(fieldName => [fieldName, getDatasetField(dataset, fieldName)])
// .filter(([fieldName, field]) => !field.statistics || field.statistics.values.min !== field.statistics.values.max)
// .forEach(([fieldName, field]) => {
const field = getDatasetField(dataset, fieldName);
// const fieldStats = field.statistics.values;
const item = document.createElement('calcite-dropdown-item');
item.innerHTML = `${field.alias || fieldName}`;
if (fieldStats && fieldStats.values && fieldStats.values.min != null && fieldStats.values.max != null) {
if (field.simpleType === 'numeric') {
// TODO: vary precision based on value range
item.innerHTML += `<br><small>(${fieldStats.values.min.toFixed(2)} to ${fieldStats.values.max.toFixed(2)})</small>`;
} else if (field.simpleType === 'date') {
item.innerHTML += ` (${formatDate(fieldStats.values.min)} to ${formatDate(fieldStats.values.max)})`;
}
} else if (fieldStats && fieldStats.uniqueCount && field.simpleType === 'string') {
item.innerHTML += ` (${fieldStats.uniqueCount} values)`;
}
// add icon for field type
if (field.simpleType === 'numeric') {
item.iconEnd = 'number';
} else if (field.simpleType === 'string') {
item.iconEnd = 'description';
} else if (field.simpleType === 'date') {
item.iconEnd = 'calendar';
}
item.setAttribute('data-field', field.name);
attributeList.appendChild(item);
});
return attributeList;
}
// add event listener to dropdown, to create visualizations
attributeList.addEventListener('calciteDropdownItemSelected', makeWidget);
// WIDGET HELPERS
//
function updateOthers(otherWidgets, layerView, whereClause, features) {
for (var x = 0; x < otherWidgets.length; x++) {
// can't update TimeSliders
if (otherWidgets[x].label == "TimeSlider") continue;
updateHistogram(otherWidgets[x], layerView, otherWidgets[x].fieldName, whereClause, features);
}
}
const throttledUpdateOthers = _.throttle(updateOthers, 100, {trailing: false});
// list all known widget DOM elements
function listWidgetElements() {
return document.getElementById('widgets').querySelectorAll('[whereClause]')
}
// concatenate all the where clauses from all the widgets
function concatWheres() {
let whereClause = '';
let widgets = listWidgetElements();
// generate master here clause with simple string concatenation
for (var x = 0; x < widgets.length; x++) {
if (x > 0) whereClause += ' AND ';
whereClause += '(' + widgets[x].getAttribute('whereClause') + ')';
}
return whereClause;
}
// STYLING FUNCTIONS
//
// add item to styling attribute dropdown
function updateStylingAttributeList (widget) {
// debugger
const list = document.querySelector('#stylingAttributeList > calcite-dropdown-group');
const item = document.createElement('calcite-dropdown-item');
item.innerHTML = widget.fieldName;
item.setAttribute('data-field', widget.fieldName);
list.appendChild(item);
}
// add event listener to dropdown, to create visualizations
stylingAttributeList.addEventListener('calciteDropdownItemSelected', updateStyle);
function updateStyle() {
}
// update the map view with a new where clause
async function updateLayerViewEffect(layerView, { where = null, updateExtent = false } = {}) {
layerView.filter = null;
if (where) {
layerView.effect = {
filter: {
where,
// geometry: layerView.view.extent.clone().expand(0.5) // testing limiting query by geom/viewport
},
excludedEffect: 'grayscale(100%) brightness(0%) opacity(25%)'
};
}
// adjust view extent (in or out) to fit all filtered data
if (updateExtent && layerView.effect && layerView.effect.filter) {
try {
const featureExtent = await layer.queryExtent({
where: layerView.effect.filter.where,
outSpatialReference: layerView.view.spatialReference
});
if (featureExtent.count > 0) {
const extent = featureExtent.extent;
// const extent = webMercatorUtils.project(featureExtent.extent, layerView.view.spatialReference);
const expanded = extent.expand(1.10);
// view.extent =
if (!layerView.view.extent.contains(expanded) ||
(expanded.width * expanded.height) / (layerView.view.extent.width * layerView.view.extent.height) < 0.20) {
layerView.view.goTo(expanded, { duration: 350 });
}
}
} catch(e) {
console.log('could not query or project feature extent to update viewport', e);
}
}
}
// make an appropriate widget for a field's data type - fieldName may be passed in directly for testing
async function makeWidget (event, fieldName = null) {
// fieldName is normally the current value of the fields dropdown
fieldName = (fieldName === null) ? event.target.getAttribute('data-field') : fieldName;
const field = getDatasetField(dataset, fieldName);
// document.querySelector('#attributeListButton').innerHTML = fieldName;
// stop any timeSlider playback
stopTimePlayback();
// clear previous filters
updateLayerViewEffect(layerView, { updateExtent: true });
let widget;
if (field.simpleType === 'numeric') {
// Histogram
widget = await makeHistogramWidget({ dataset, fieldName, layer, layerView, slider: true })
}
if (field.simpleType === 'date') {
// Time slider
widget = await makeTimeSliderWidget({ dataset, fieldName, layer, layerView, slider: true });
}
widget.fieldName = fieldName;
widget.container.classList.add('widget');
// label widget
const label = document.createElement('div');
label.classList.add('widgetLabel');
label.innerHTML = fieldName;
widget.container.before(label);
// update styling attribute dropdown
updateStylingAttributeList(widget);
};
function formatDate (timestamp) {
const date = new Date(timestamp);
return `${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()}`;
// => 5/15/2020
}
function formatSQLDate (timestamp) {
const date = new Date(timestamp);
return `'${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}'`;
// => 2020-05-15
}
function makeStylingWidget() {
const container = document.createElement('div');
container.classList.add('stylingWidget');
document.getElementById('widgets').appendChild(container);
}
// TESTS
//
makeWidget(null, "locationLongitude");
// makeWidget(null, "locationLatitude");
// makeWidget(null, "parametersFuProcessing");
// makeWidget(null, "sensorPropertiesViewingAngle");
makeWidget(null, "phenomenonTime");
// makeWidget(null, "observationResult");
makeStylingWidget();
})();
</script>
</head>
<body>
<div id="sidebar">
<div id="sidebarItems">
<div id="datasetName"></div>
<div>
<span id="orgName"></span>
<span id="recordCount"></span>
</div>
<calcite-dropdown type="hover" width="l" id="attributeList">
<calcite-button id="attributeListButton" slot="dropdown-trigger">Choose an attribute:</calcite-button>
<calcite-dropdown-group></calcite-dropdown-group>
</calcite-dropdown>
<div id="widgets"></div>
<calcite-dropdown type="hover" width="l" id="stylingAttributeList">
<calcite-button id="stylingAttributeListButton" slot="dropdown-trigger">Style by attribute:</calcite-button>
<calcite-dropdown-group></calcite-dropdown-group>
</calcite-dropdown>
</div>
</div>
<div id="viewDiv"></div>
</body>
</html>