-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.html
More file actions
1989 lines (1785 loc) · 82.6 KB
/
Copy pathindex.html
File metadata and controls
1989 lines (1785 loc) · 82.6 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
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
<!--
Copyright 1995-2017 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: contracts@esri.com
-->
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Aggregation Viewer - Client Side Feature Layer</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.46/esri/css/esri.css">
<link rel="stylesheet" href="./featureServiceViewerStyles.css">
<script src="https://use.fontawesome.com/9482a0b1d1.js"></script>
<script src="https://js.arcgis.com/3.46/"></script>
<script>
require([
"dojo/parser",
"dojo/dom",
"dojo/dom-style",
"dojo/dom-class",
"dojo/on",
"dojo/json",
"dojo/_base/array",
"dojo/query",
"dojo/number",
"esri/map",
"esri/graphic",
"esri/SpatialReference",
"esri/Color",
"esri/request",
"esri/geometry/webMercatorUtils",
"esri/geometry/Extent",
"esri/tasks/GeometryService",
"esri/InfoTemplate",
"esri/TimeExtent",
"esri/graphicsUtils",
"esri/IdentityManager",
"esri/layers/FeatureLayer",
"esri/layers/LabelClass",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/TextSymbol",
"esri/geometry/Polygon",
"esri/dijit/TimeSlider",
"esri/renderers/HeatmapRenderer",
"esri/renderers/ClassBreaksRenderer",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/TitlePane",
"dijit/TooltipDialog",
"dijit/form/DropDownButton",
"dijit/form/Select",
"dojo/query!css2",
"dojo/domReady!"
], function (
parser, dom, domStyle, domClass, on, JSON, array, domQuery, number,
Map, Graphic, SpatialReference, Color, esriRequest, webMercatorUtils, Extent, GeometryService, InfoTemplate, TimeExtent, graphicsUtils,
IdentityManager,
FeatureLayer, LabelClass, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer,
SimpleLineSymbol, SimpleFillSymbol, TextSymbol, Polygon,
TimeSlider,
HeatmapRenderer, ClassBreaksRenderer,
BorderContainer, ContentPane, TitlePane, TooltipDialog, DropDownButton, Select) {
parser.parse();
// ### global variables ###
let _map;
let _layerTimeExtent;
let _replay = false;
let _live = false;
let _startTimeSlider = true;
let _minValue;
let _maxValue;
let _ignoreChangeEvent = false;
let _layerInfo;
let _timeSlider;
const _binRendererProps = {};
// ### Spatial Reference variables ###
// These variables manage coordinate system transformations and spatial reference handling
const _defaultWkid = 102100; // Web Mercator - default coordinate system
let _wkid = 102100; // Current working coordinate system ID
let _currentMapSR = 102100; // Current map spatial reference system
// ### Geometry Service for spatial reference transformations ###
const _gs = new GeometryService("https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer");
// Define _isBasemapTiled with a default value
let _isBasemapTiled = true; // Set to true if tiled basemaps are the default, otherwise false
//#############################################################################################
// Map Related functions
//#############################################################################################
esri.config.defaults.io.corsEnabledServers.push('http://storm.esri.com');
esri.config.defaults.io.corsEnabledServers.push('http://storm.esri.com:6080');
esri.config.defaults.io.corsEnabledServers.push('https://storm.esri.com:6443');
esri.config.defaults.io.corsEnabledServers.push('http://localhost:9000');
// ### Initialize map with default extent ###
const initMapExtent = new Extent({
"xmin": -20037508.342787,
"ymin": -20037508.342787,
"xmax": 20037508.342787,
"ymax": 20037508.342787,
"spatialReference": {"wkid": _defaultWkid}
});
// Build initial map with the default extent
buildMap(initMapExtent);
/**
* Builds or rebuilds the map with the specified extent and current spatial reference
* This function destroys any existing map and creates a new one with proper spatial reference
* @param {Extent} mapExtent - The extent to set for the new map
*/
function buildMap(mapExtent) {
if (_map) {
// Destroy existing map if it exists
_map.removeAllLayers();
_map.destroy();
_map = null;
console.log("Destroyed previous map instance for spatial reference change");
}
// Create new map with the specified extent
_map = new Map("map", {
wrapAround180: true,
extent: mapExtent,
showLabels: true,
showAttribution: false,
sliderStyle: "small"
});
_map.on("load", function () {
console.log("Map loaded successfully.");
setFeatureLayers();
});
// Attach extent change handler
attachMapExtentChangeHandler();
// Add the basemap
const basemapUrl = dom.byId("basemapUrl").value;
let basemapLayer;
basemapLayer = new ArcGISDynamicMapServiceLayer(basemapUrl, {
"showAttribution": false,
"opacity": 1.0
});
_map.addLayers([basemapLayer]);
// only the first map built is tiled
_isBasemapTiled = false;
}
/**
* Issue new query on extent-change if live mode is disabled ###
* Note: This event handler will be re-attached when map is rebuilt
*/
function attachMapExtentChangeHandler() {
_map.on("extent-change", function (evt) {
if (_map.getLayer("aggregations") && !_ignoreChangeEvent && !_live) {
updateLayerFromUIChange();
}
});
}
//#############################################################################################
// UI Related functions
//#############################################################################################
/*
* DRY: Reusable section toggle function
* This function creates a toggle handler for a section based on its ID and visibility state
* @param {string} sectionId - The ID of the section to toggle
* @param {string} toggleId - The ID of the toggle button
* @param {Object} visibilityVar - An object to track the visibility state of the section
*/
function createSectionToggle(sectionId, toggleId, visibilityVar) {
return function () {
// toggle section visibility
if (visibilityVar.value) {
domClass.add(dojo.byId(sectionId), "section-hidden");
domClass.replace(domQuery("#" + toggleId + " i")[0], "fa-chevron-down", "fa-chevron-up");
} else {
domClass.remove(dojo.byId(sectionId), "section-hidden");
domClass.replace(domQuery("#" + toggleId + " i")[0], "fa-chevron-up", "fa-chevron-down");
}
visibilityVar.value = !visibilityVar.value;
};
}
// ### Section visibility state objects ###
const layersVisibility = { value: true };
const aggSettingsVisibility = { value: true };
const aggStyleVisibility = { value: false };
const aggBinsVisibility = { value: true };
const streamingModeVisibility = { value: true };
const aggLabelsVisibility = { value: true };
//#############################################################################################
// ### UI Event Listeners ###
//#############################################################################################
// ### Section toggle event handlers ###
on(dojo.byId("layersToggle"), "click", createSectionToggle("layersSection", "layersToggle", layersVisibility));
on(dojo.byId("aggSettingsToggle"), "click", createSectionToggle("aggSettingsSection", "aggSettingsToggle", aggSettingsVisibility));
on(dojo.byId("aggStyleToggle"), "click", createSectionToggle("aggStyleSection", "aggStyleToggle", aggStyleVisibility));
on(dojo.byId("aggBinsToggle"), "click", createSectionToggle("aggBinsSection", "aggBinsToggle", aggBinsVisibility));
on(dojo.byId("streamingModeToggle"), "click", createSectionToggle("streamingModeSection", "streamingModeToggle", streamingModeVisibility));
on(dojo.byId("aggLabelsToggle"), "click", createSectionToggle("aggLabelsMainSection", "aggLabelsToggle", aggLabelsVisibility));
on(dojo.byId("setLayerButton"), "click", setFeatureLayers);
on(dojo.byId("heatmap"), "change", toggleHeatmap);
on(dojo.byId("refreshMode"), "change", toggleMode);
on(dojo.byId("autoOffSet"), "change", toggleRefresh);
on(dojo.byId("lodType"), "change", toggleRefresh);
on(dojo.byId("lodGeometryAggregationType"), "change", toggleRefresh);
on(dojo.byId("lod"), "change", toggleRefresh);
on(dojo.byId("blurRadius"), "change", toggleRefresh);
on(dom.byId("useStats"), "change", toggleStats);
on(dijit.byId("statField"), "change", statFieldChanged);
on(dijit.byId("statType"), "change", updateLayerFromUIChange);
// ### Spatial Reference event handlers ###
on(dijit.byId("spatialReferenceSelect"), "change", onSpatialReferenceChange);
// ### Aggregation Renderer event handlers ###
on(dojo.byId("useAggregationRenderer"), "change", toggleUseAggregationRenderer);
on(dojo.byId("minColor"), "change", updateRendererFromUI);
on(dojo.byId("maxColor"), "change", updateRendererFromUI);
on(dojo.byId("minColorA"), "change", updateRendererFromUI);
on(dojo.byId("maxColorA"), "change", updateRendererFromUI);
on(dojo.byId("minOutlineColor"), "change", updateRendererFromUI);
on(dojo.byId("maxOutlineColor"), "change", updateRendererFromUI);
on(dojo.byId("minOutlineColorA"), "change", updateRendererFromUI);
on(dojo.byId("maxOutlineColorA"), "change", updateRendererFromUI);
on(dojo.byId("minOutlineWidth"), "change", updateRendererFromUI);
on(dojo.byId("maxOutlineWidth"), "change", updateRendererFromUI);
on(dojo.byId("minSize"), "change", updateRendererFromUI);
on(dojo.byId("maxSize"), "change", updateRendererFromUI);
on(dojo.byId("minValue"), "change", updateRendererFromUI);
on(dojo.byId("maxValue"), "change", updateRendererFromUI);
on(dojo.byId("classBreaksCount"), "change", updateRendererFromUI);
// ### Aggregation Labels event handlers ###
on(dojo.byId("renderLabels"), "change", updateRendererFromUI);
on(dijit.byId("labelFont"), "change", updateRendererFromUI);
on(dijit.byId("labelStyle"), "change", updateRendererFromUI);
on(dijit.byId("labelWeight"), "change", updateRendererFromUI);
on(dojo.byId("labelSize"), "change", updateRendererFromUI);
on(dojo.byId("labelColor"), "change", updateRendererFromUI);
on(dojo.byId("labelOpacity"), "change", updateRendererFromUI);
// ### LOD SR event handlers ###
on(dijit.byId("lodSR"), "change", updateLayerFromUIChange);
on(dojo.byId("useLodSR"), "change", updateLayerFromUIChange);
on(document.getElementsByClassName("collapser")[0], "click", togglePanel);
/**
* Shows a tooltip with the current value of the input field
* This function is called when the mouse enters the input field
*/
on(dom.byId("inputUrl"), "mouseenter", function() {
this.title = this.value || "No value entered";
});
/**
* Clears the tooltip when the mouse leaves the input field
* This function is called when the mouse leaves the input field
*/
on(dom.byId("inputUrl"), "mouseleave", function() {
this.title = "";
});
/**
* Updates the feature layers based on the current UI settings
* This function is called when the user clicks the "Set Layer" button
*/
function setFeatureLayers() {
// Remove existing feature layers
const existingAggregationLayer = _map.getLayer("aggregations");
if (existingAggregationLayer) {
_map.removeLayer(existingAggregationLayer);
} else {
console.log("Aggregation layer not found.");
}
const heatmapLayer = _map.getLayer("heatmap");
if (heatmapLayer) {
_map.removeLayer(heatmapLayer);
} else {
console.log("Heatmap layer not found.");
}
const newAggregationLayer = addAggregationsLayer();
newAggregationLayer.on("load", function () {
queryLayerTimeExtent();
addHeatmapLayer();
updateLayerFromUIChange(true);
});
}
/**
* Toggles the visibility of the panel by adding or removing a CSS class
* This function is used to collapse or expand the panel
*/
function togglePanel() {
domClass.toggle(document.getElementsByTagName("body")[0], "panel-collapsed");
}
// ### Switch change functions ###
/*
* Toggles the map interaction mode between manual, live, and replay
* This function is called when the mode switch is changed
*/
function toggleMode(evt) {
if (evt.target.value === "manual") {
_live = false;
_replay = false;
domStyle.set(dom.byId('timeSlider'), "display", 'none');
_map.setTimeSlider(null);
_map.setTimeExtent(null);
updateLayerFromUIChange();
} else if (evt.target.value === "live") {
_live = true;
_replay = false;
autoUpdate();
domStyle.set(dom.byId('timeSlider'), "display", 'none');
_map.setTimeSlider(null);
_map.setTimeExtent(null);
} else if (evt.target.value === "replay") {
_live = false;
_replay = true;
if (_startTimeSlider) {
initTimeSlider();
_startTimeSlider = false;
} else {
_ignoreChangeEvent = true;
updateTimeSlider();
}
domStyle.set(dom.byId('timeSlider'), "display", 'block');
}
}
/**
* Toggles the heatmap layer on and off
* This function is called when the heatmap toggle is changed
*/
function toggleHeatmap(evt) {
if (dojo.byId("heatmap").checked === true) {
dojo.byId("radius").style.display = "inherit";
const layer = _map.getLayer("heatmap");
const minIsFinit = isFinite(_minValue);
const maxIsFinit = isFinite(_maxValue);
if (!minIsFinit) {
_minValue = 0;
}
if (!maxIsFinit) {
_maxValue = 1;
}
layer.renderer.setMinPixelIntensity(_minValue);
layer.renderer.setMaxPixelIntensity(_maxValue);
} else {
dojo.byId("radius").style.display = "none";
}
updateLayerFromUIChange();
}
/**
* Toggles the refresh of the layer
* This function is called when the refresh toggle is changed
*/
function toggleRefresh(evt) {
if (!_live) {
updateLayerFromUIChange();
}
}
/**
* Toggles the use of the aggregation renderer
* This function is called when the useAggregationRenderer toggle is changed
*/
function toggleStats(evt) {
if (evt.target.id === "useStats") {
if (dojo.byId("useStats").checked === true) {
dojo.byId("statField").style.display = "block";
dojo.byId("statType").style.display = "block";
} else {
dojo.byId("statField").style.display = "none";
dojo.byId("statType").style.display = "none";
}
updateLayerFromUIChange();
}
}
/**
* Handles changes to the selected statistical field
* This function is called when the statistical field dropdown is changed
*/
function statFieldChanged(val) {
const control = dijit.byId('statField');
const selectedOption = control.getOptions(val);
populateStatTypeSelectOptions(selectedOption);
updateLayerFromUIChange();
}
//#############################################################################################
// ### Spatial Reference Functions ###
//#############################################################################################
/**
* Handles spatial reference system changes from the dropdown
* Updates global variables and re-projects map if necessary
* @param {string|number} newWkid - The new spatial reference WKID
*/
function onSpatialReferenceChange(newWkid) {
_wkid = parseInt(newWkid);
// Check if the map's current spatial reference matches the new one
if (_map && _map.spatialReference && _wkid === _map.spatialReference.wkid) {
return; // No need to rebuild the map
}
// Update the current map spatial reference
_currentMapSR = _wkid;
// Project the map's current extent to the new spatial reference
projectMapToSR(_wkid);
}
/**
* Projects the current map extent to a new spatial reference system using geometry service
* @param {number} wkid - The target spatial reference WKID
*/
function projectMapToSR(wkid) {
const sr = new SpatialReference(wkid);
const project = _gs.project([_map.extent], sr);
project.then(function (result) {
if (result.length) {
const newMapExtent = result[0];
buildMap(newMapExtent); // Rebuild the map with the new extent
} else {
console.log("Projection was successful, but no results were returned.");
}
}, function (err) {
console.log("Project Map to SR failed: ", err);
// Fallback: build map with default extent for the new spatial reference
const defaultExtent = new Extent({
"xmin": -20037508.342787,
"ymin": -20037508.342787,
"xmax": 20037508.342787,
"ymax": 20037508.342787,
"spatialReference": { "wkid": wkid }
});
buildMap(defaultExtent);
});
}
//#############################################################################################
// ### Aggregation Labels Functions ###
//#############################################################################################
/**
* Toggles the visibility of aggregation labels and their control panel
* @param {Event} evt - The change event from the checkbox
*/
function toggleLabels(evt) {
// Toggle label visibility and show/hide label controls
if (evt.target.id === "renderLabels") {
if (dojo.byId("renderLabels").checked === true) {
dojo.byId("aggLabelsSection").style.display = "block";
} else {
dojo.byId("aggLabelsSection").style.display = "none";
}
updateLayerFromUIChange();
}
}
/**
* Populates the statistical type select options based on the selected field
* @param {Object} selectedOption - The selected field option
*/
function populateStatTypeSelectOptions(selectedOption) {
const statTypeSelect = dijit.byId("statType");
// clear statTypeSelect
statTypeSelect.removeOption(statTypeSelect.getOptions());
// find the field by name
const statFieldElement = dijit.byId("statField");
if (!statFieldElement) {
console.warn("Element with ID 'statField' not found.");
return;
}
const fieldName = statFieldElement.value;
let field = null;
for (let i = 0; i < _layerInfo.fields.length; i++) {
const currentField = _layerInfo.fields[i];
if (currentField.name === fieldName)
field = currentField;
}
if (isFieldNumeric(field)) {
// add all types
const options = [ {'label':'Average', 'value':'avg'},
{'label':'Maximum', 'value':'max'},
{'label':'Minimum', 'value':'min'},
{'label':'Standard Deviation', 'value':'stddev'},
{'label':'Sum', 'value':'sum'},
{'label':'Variance', 'value':'var'},
{'label':'Count Distinct', 'value':'countdistinct'},
{'label':'Count', 'value':'count'} ];
statTypeSelect.addOption(options);
} else {
// add only the count and count distinct types
const options = [ {'label':'Count Distinct', 'value':'countdistinct'},
{'label':'Count', 'value':'count'} ];
statTypeSelect.addOption(options);
}
updateLayerFromUIChange();
}
function getLayerInfo() {
const url = dojo.byId("inputUrl").value;
const mapServiceInfoDeferred = esri.request({
url: url,
content: {
f: 'json'
},
callbackParamName: "callback"
});
mapServiceInfoDeferred.then(function (response) {
_layerInfo = response;
populateDijitSelectWithLayerFields(dijit.byId('statField'), false);
statFieldChanged(dijit.byId('statField').value); // to init-populate the stat types control
}
);
}
function populateDijitSelectWithLayerFields(select, numericOnly) {
// clear exiting options
select.removeOption(select.getOptions());
// populate options based on the _layerInfo.fields array
for (let i = 0; i < _layerInfo.fields.length; i++) {
const field = _layerInfo.fields[i];
const fieldType = field.type.substring(13);
const option = {'label': field.name + " " + "<em class='fieldTypeSelect'>" + fieldType + '</em>', 'value': field.name, 'type': field.type };
if (numericOnly) {
if (isFieldNumeric(field))
select.addOption(option);
} else {
if (isSupportedStatField(field))
select.addOption(option);
}
}
}
/**
* Populates the select element with layer fields
* @param {Object} select - The select element to populate
* @param {boolean} numericOnly - Whether to include only numeric fields
*/
function populateSelectWithLayerFields(select, numericOnly) {
// clear exiting options
for (let i = select.options.length - 1; i >= 0; i--) {
select.remove(i);
}
// populate options based on the layerFields array
let pos = 0;
for (let i = 0; i < layerFields.length; i++) {
const field = _layerInfo.fields[i];
if (numericOnly) {
if (isFieldNumeric(field))
select.options[pos++] = new Option(field.name, field.name);
} else {
if (isSupportedStatField(field))
select.options[pos++] = new Option(field.name, field.name);
}
}
}
/**
* Checks if the field is numeric
* @param {Object} field - The field object to check
* @returns {boolean} True if the field is numeric, false otherwise
*/
function isFieldNumeric(field) {
if (!field || !field.type)
return false;
return (field.type === "esriFieldTypeSmallInteger" || field.type === "esriFieldTypeInteger" || field.type === "esriFieldTypeSingle" || field.type === "esriFieldTypeDouble" || field.type === "esriFieldTypeOID");
}
/**
* Checks if the field is supported for statistical operations
* @param {Object} field - The field object to check
* @returns {boolean} True if the field is supported, false otherwise
*/
function isSupportedStatField(field) {
if (!field || !field.type)
return false;
return (field.type !== "esriFieldTypeGeometry" && field.type !== "esriFieldTypeBlob" && field.type !== "esriFieldTypeRaster");
}
//#############################################################################################
// Layer related functions
//#############################################################################################
/**
* Adds a client-side feature layer for aggregations with a predefined feature collection and renderer
* This layer will be used to display aggregated data on the map
* @returns {FeatureLayer} The created FeatureLayer instance
*/
function addAggregationsLayer() {
const layerDefinition = {
"geometryType": "esriGeometryPolygon",
"fields": [
{
"name": "objectid",
"type": "esriFieldTypeInteger",
"alias": "objectid"
}, {
"name": "Geohash",
"type": "esriFieldTypeString",
"alias": "Geohash"
}, {
"name": "Count",
"type": "esriFieldTypeInteger",
"alias": "Count"
}, {
"name": "Weight",
"type": "esriFieldTypeDouble",
"alias": "Weight"
}, {
"name": "Geometry",
"type": "esriFieldTypeGeometry",
"alias": "Geometry"
}
]
};
const featureCollection = {
layerDefinition: layerDefinition,
featureSet: {
features: [],
geometryType: layerDefinition.geometryType
}
};
const infoTemplate = new InfoTemplate("Attributes", "${*}");
const aggregationLayer = new FeatureLayer(featureCollection, {
id: "aggregations",
objectIdField: "objectid",
showLabels: true,
infoTemplate: infoTemplate,
outFields: ["*"]
});
// Create and set the bins renderer
const renderer = dojo.byId("useAggregationRenderer").checked === true ? createAggregationRenderer() : createClassBreakRenderer();
aggregationLayer.setRenderer(renderer);
// Create and set the bin labels (if renderLabels is checked)
if (dojo.byId("renderLabels") && dojo.byId("renderLabels").checked === true) {
const labelClass = createLabelClass();
aggregationLayer.setLabelingInfo([labelClass]);
}
_map.addLayer(aggregationLayer);
console.log("Client Aggregation Layer added");
getLayerInfo();
return aggregationLayer
}
/**
* Adds a heatmap layer to the map with a predefined feature collection and renderer
*/
function addHeatmapLayer() {
const layerDefinition = {
"geometryType": "esriGeometryPoint",
"fields": [{
"name": "objectid",
"type": "esriFieldTypeInteger",
"alias": "objectid"
}, {
"name": "Geohash",
"type": "esriFieldTypeString",
"alias": "Geohash"
}, {
"name": "Count",
"type": "esriFieldTypeInteger",
"alias": "Count"
}, {
"name": "Weight",
"type": "esriFieldTypeDouble",
"alias": "Weight"
}, {
"name": "geometry",
"type": "esriFieldTypeGeometry",
"alias": ""
}]
};
const featureCollection = {
layerDefinition: layerDefinition,
featureSet: {
features: [],
geometryType: layerDefinition.geometryType
}
};
const heatmapLayer = new FeatureLayer(featureCollection, {
id: "heatmap",
objectIdField: "objectid",
visible: true,
opacity: 1
});
// Create and set the renderer for the heatmap layer
const renderer = createHeatmapRenderer();
heatmapLayer.setRenderer(renderer);
_map.addLayer(heatmapLayer);
console.log("Heatmap Layer added");
}
/**
* Queries the feature layer's time extent and sets the global _layerTimeExtent variable
* This function is called when the map is loaded or when the layer is set
*/
function queryLayerTimeExtent() {
const url = dojo.byId("inputUrl").value + "?f=json";
const request = esriRequest({
"url": url,
"handleAs": "json",
"callbackParamName": "callback"
});
request.then(
function (response) {
_layerTimeExtent = new TimeExtent(new Date(response.timeInfo.timeExtent[0]), new Date(response.timeInfo.timeExtent[1]));
},
function (error) {
console.log("Error getting the layers time extent: ", error.message);
});
}
/**
* Loads the properties for the bin renderer from the UI inputs
* This function reads values from the input fields and sets them in the _binRendererProps object
* It is called when the aggregation renderer is used or when the properties need to be
*/
function loadBinRendererProps() {
_binRendererProps.classBreaksCount = dojo.byId("classBreaksCount") ? dojo.byId("classBreaksCount").value : 10;
console.log("Creating an aggregation renderer with " + _binRendererProps.classBreaksCount + " class breaks");
// min and max fill color and opacity
const minColorHex = dojo.byId("minColor") ? dojo.byId("minColor").value : "#000000";
const maxColorHex = dojo.byId("maxColor") ? dojo.byId("maxColor").value : "#000000";
let minColorA = dojo.byId("minColorA") ? parseFloat(dojo.byId("minColorA").value / 255) : 1.0;
if (isNaN(minColorA) || minColorA < 0 || minColorA > 1) {
minColorA = 1.0; // Default to fully opaque if invalid
}
let maxColorA = dojo.byId("maxColorA") ? parseFloat(dojo.byId("maxColorA").value / 255) : 1.0;
if (isNaN(maxColorA) || maxColorA < 0 || maxColorA > 1) {
maxColorA = 1.0; // Default to fully opaque if invalid
}
_binRendererProps.minColor = hexToRgba(minColorHex, minColorA);
_binRendererProps.maxColor = hexToRgba(maxColorHex, maxColorA);
// min and max outline color and opacity
const minOutlineColorHex = dojo.byId("minOutlineColor") ? dojo.byId("minOutlineColor").value : "#000000";
const maxOutlineColorHex = dojo.byId("maxOutlineColor") ? dojo.byId("maxOutlineColor").value : "#000000";
let minOutlineColorA = dojo.byId("minOutlineColorA") ? parseFloat(dojo.byId("minOutlineColorA").value / 255) : 1.0;
if (isNaN(minOutlineColorA) || minOutlineColorA < 0 || minOutlineColorA > 1) {
minOutlineColorA = 1.0; // Default to fully opaque if invalid
}
let maxOutlineColorA = dojo.byId("maxOutlineColorA") ? parseFloat(dojo.byId("maxOutlineColorA").value / 255) : 1.0;
if (isNaN(maxOutlineColorA) || maxOutlineColorA < 0 || maxOutlineColorA > 1) {
maxOutlineColorA = 1.0; // Default to fully opaque if invalid
}
_binRendererProps.minOutlineColor = hexToRgba(minOutlineColorHex, minOutlineColorA);
_binRendererProps.maxOutlineColor = hexToRgba(maxOutlineColorHex, maxOutlineColorA);
// min and max outline width
_binRendererProps.minOutlineWidth = dojo.byId("minOutlineWidth") ? parseFloat(dojo.byId("minOutlineWidth").value) : 0.5;
_binRendererProps.maxOutlineWidth = dojo.byId("maxOutlineWidth") ? parseFloat(dojo.byId("maxOutlineWidth").value) : 1.0;
}
/**
* Interpolates a value between min and max.
* @param {number} ratio - A value between 0 and 1
* @param {number} min - The minimum value
* @param {number} max - The maximum value
* @returns {number} A value between min and max
*/
function interpolate(ratio, min, max) {
if (max === min) return max;
return min + ratio * (max - min);
}
/**
* Creates class break information for the renderer.
* @param {number} min - The minimum value for the class break
* @param {number} max - The maximum value for the class break
* @returns {Object} An object containing the class break information
*/
function createClassBreakInfo(min, max) {
const ratio = max / 100;
// fill color and opacity
const fillR = interpolate(ratio, _binRendererProps.minColor[0], _binRendererProps.maxColor[0]);
const fillG = interpolate(ratio, _binRendererProps.minColor[1], _binRendererProps.maxColor[1]);
const fillB = interpolate(ratio, _binRendererProps.minColor[2], _binRendererProps.maxColor[2]);
const fillA = interpolate(ratio, _binRendererProps.minColor[3], _binRendererProps.maxColor[3]);
const fillColor = new Color([fillR, fillG, fillB, fillA]);
const fillSymbol = new SimpleFillSymbol();
// outline color and width
const outlineR = interpolate(ratio, _binRendererProps.minOutlineColor[0], _binRendererProps.maxOutlineColor[0]);
const outlineG = interpolate(ratio, _binRendererProps.minOutlineColor[1], _binRendererProps.maxOutlineColor[1]);
const outlineB = interpolate(ratio, _binRendererProps.minOutlineColor[2], _binRendererProps.maxOutlineColor[2]);
const outlineA = interpolate(ratio, _binRendererProps.minOutlineColor[3], _binRendererProps.maxOutlineColor[3]);
const outlineColor = new Color([outlineR, outlineG, outlineB, outlineA]);
const outlineWidth = interpolate(ratio, _binRendererProps.minOutlineWidth, _binRendererProps.maxOutlineWidth);
fillSymbol
.setStyle(SimpleFillSymbol.STYLE_SOLID)
.setColor(fillColor)
.setOutline(
new SimpleLineSymbol().setColor(outlineColor).setWidth(outlineWidth)
);
return {
minValue: min,
maxValue: max,
symbol: fillSymbol
};
}
/**
* Builds class break infos for the aggregation renderer based on the bin renderer properties
* This function creates an array of class break infos with interpolated colors and sizes
* @returns {Array} An array of class break info objects
*/
function buildAggregationRendererClassBreakInfos() {
loadBinRendererProps();
const classBreakInfos = [];
const classSize = 100 / _binRendererProps.classBreaksCount;
for (let i = 0; i < _binRendererProps.classBreaksCount; i++) {
classBreakInfos.push(createClassBreakInfo(i * classSize, (i + 1) * classSize));
}
return classBreakInfos;
}
/**
* Builds class break infos for a simple aggregation renderer with fixed breaks
* This function creates an array of class break infos with predefined ranges
* This is used for the simple aggregation renderer example
* It creates fixed class breaks for demonstration purposes
* It does not use the bin renderer properties
* @returns {Array} An array of class break info objects
*/
function buildAggregationRendererClassBreakInfos_Simple() {
loadBinRendererProps();
const classBreakInfos = [];
classBreakInfos.push(createClassBreakInfo(0, 10));
classBreakInfos.push(createClassBreakInfo(10, 20));
classBreakInfos.push(createClassBreakInfo(20, 30));
classBreakInfos.push(createClassBreakInfo(30, 40));
classBreakInfos.push(createClassBreakInfo(40, 50));
classBreakInfos.push(createClassBreakInfo(50, 60));
classBreakInfos.push(createClassBreakInfo(60, 70));
classBreakInfos.push(createClassBreakInfo(70, 80));
classBreakInfos.push(createClassBreakInfo(80, 90));
classBreakInfos.push(createClassBreakInfo(90, 100));
return classBreakInfos;
}
/**
* Creates a ClassBreaksRenderer for the aggregation layer
* This renderer defines different color breaks based on the "Weight" field
* @returns {ClassBreaksRenderer} The created ClassBreaksRenderer instance
*/
function createAggregationRenderer() {
const classBreakInfos = buildAggregationRendererClassBreakInfos();
// define breaks and color
const renderer = new ClassBreaksRenderer({
field: "Weight",
defaultSymbol: createClassBreakInfo(90, 100).symbol,
normalizationType: "percent-of-total",
normalizationTotal: 100,
classBreakInfos: classBreakInfos
});
return renderer;
}
/**
* Creates a ClassBreaksRenderer for the aggregation layer
* This renderer defines different color breaks based on the "Weight" field
* @returns {ClassBreaksRenderer} The created ClassBreaksRenderer instance
*/
function createClassBreakRenderer() {
console.log("Creating a class break renderer with 10 classes");
// define default symbol
const symbol = new SimpleFillSymbol();
symbol.setColor(new Color([150, 150, 150, 0.3]))
.setOutline(new SimpleLineSymbol().setColor(new Color("white")).setWidth(0.3));
// function to create symbol for breaks with a given color
function createSymbol(color) {
return new SimpleFillSymbol()
.setColor(color)
.setOutline(
new SimpleLineSymbol().setColor(new Color([99, 99, 99, 1])).setWidth(0.3)
);
};
const classColorInfo = [];
// define breaks and color
const renderer = new ClassBreaksRenderer({
field: "Weight",
defaultSymbol: symbol,
normalizationType: "percent-of-total",
normalizationTotal: 100,
classBreakInfos: [
{
minValue: 0,
maxValue: 10,
symbol: createSymbol(new Color([254, 240, 217, 0.7]))
},
{
minValue: 10,
maxValue: 20,
symbol: createSymbol(new Color([253, 212, 158, 0.7]))
},
{
minValue: 20,
maxValue: 30,
symbol: createSymbol(new Color([253, 187, 132, 0.8]))
},
{
minValue: 30,
maxValue: 40,
symbol: createSymbol(new Color([252, 141, 89, 0.8]))
},
{
minValue: 40,
maxValue: 60,
symbol: createSymbol(new Color([239, 101, 72, 0.9]))
},
{
minValue: 60,
maxValue: 80,