-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
944 lines (864 loc) · 34.2 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow" />
<title>Wild Ocean Spots</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<!-- Styles -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/3.3.0/mapbox-gl.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.8.0/nouislider.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/css/select2.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-5-theme/1.3.0/select2-bootstrap-5-theme.min.css" />
<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/3.3.0/mapbox-gl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
<!-- we need the bootstrap bundle to include popper for dropdowns -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<!-- big shout out to leon gersen for merging my pull request to support inverted connects -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.8.0/nouislider.min.js"></script>
<!-- I wish select2 would implement my patches aswell, but the project is dead -->
<script src="select2.optgroup.js"></script>
<script>
function throttle(f, delay) {
let lastCall = -Infinity;
let wait;
let handle;
return (...args) => {
wait = lastCall + delay - Date.now();
clearTimeout(handle);
handle = setTimeout(() => {
f(...args);
lastCall = Date.now();
}, wait);
};
}
const escapeId = id => id.replace(/\s/g,'_');
$.fn.join = function(separator) {
return $('<div>').append(this.toArray().flatMap((e, i) => [separator.clone(), e]).slice(1));
};
Array.prototype.remove = function(condition) {
const indexElement = this.findIndex(condition);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
function observeWidth(element, callback) {
let oldWidth = $(element).width();
if (window.ResizeObserver) {
new ResizeObserver(entries => {
const cBS = entries[0].contentBoxSize;
if (cBS) {
const width = cBS[0].inlineSize;
callback(width, oldWidth);
oldWidth = width;
}
})
.observe(element);
}
}
</script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
/* ignore dark mode for the species icons */
img { color-scheme: only light !important; }
.select2-container--bootstrap-5.select2-container--focus .select2-selection {
border-color: #86b7fe;
}
.select2-container--bootstrap-5.select2-container--open .select2-selection {
border-color: #86b7fe;
/* clip the bottom of the border and box-shadow of the select container when dropdown is shown */
-webkit-clip-path: inset(-5px -5px 0px -5px);
clip-path: inset(-5px -5px 0px -5px);
}
.select2-container.select2-container--bootstrap-5:not(.select2) > * {
/* give the dropdown the same box-shadow like the select container */
box-shadow: 0 0 0 .25rem rgba(13, 110, 253, .25);
border: 1px solid #86b7fe;
border-top: 0;
}
.select2-container.select2-container--bootstrap-5:not(.select2) > *:last-child {
/* clip the top box shadow */
-webkit-clip-path: inset(0px -5px -5px -5px);
clip-path: inset(0px -5px -5px -5px);
border: 1px solid #86b7fe;
/* round bottom edges for the last dropdown element */
border-radius: 0 0 0.25rem 0.25rem;
}
.select2-container.select2-container--bootstrap-5:not(.select2) > *:not(:last-child) {
/* clip top and bottom box shadow of all dropdown elements except the last one */
-webkit-clip-path: inset(0 -5px 0 -5px);
clip-path: inset(0 -5px 0 -5px);
border-bottom: 0;
}
.select2-container--bootstrap-5 .select2-dropdown {
border: none;
}
.select2-results__group {
font-weight: bold !important;
}
.select2-selection--multiple .select2-selection__rendered .select2-selection__choice {
/* remove the padding so that the whole row can get highlighted */
padding: 0em 0em !important;
margin-right: 0.375rem !important;
margin-bottom: 0rem !important;
}
/* overwriting the select2 bootstrap 5 theme */
.select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__rendered .select2-selection__choice .select2-selection__choice__remove:hover {
background: initial;
}
.select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__rendered .select2-selection__choice .select2-selection__choice__remove {
all: initial;
margin-inline: 0.25em;
cursor: pointer;
}
.select2-selection__choice__display img {
/* stretching the icons to set height with the original img ratio */
object-fit: contain;
height: 1.5rem;
/* max-width: 1.5rem; */
}
.select2-selection__choice__text {
/* margin-right: 0.25em; we use the icon margin for padding*/
/* keep space separated options in one row */
white-space: nowrap;
}
.select2-results__image {
height: 1.5rem;
}
.select2-results__option {
padding-top: 0;
padding-bottom: 0;
}
.dropdown-menu {
max-width: 30rem; /* to be changed */
}
.dropdown-item:active {
/* removing the blue highlight background when dragging slider */
background-color: initial;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="container-fluid">
<nav class="navbar navbar-expand navbar-light flex-nowrap">
<ul class="navbar-nav align-top">
<li class="nav-item dropdown"></li>
<select multiple='multiple' id='species-filter' class="form-control"></select>
</li>
</ul>
<!-- ms-auto aligns it to the right, ps-3 gives padding bewteen the left nav -->
<ul class="navbar-nav ps-3 align-items-start ms-auto">
<li class="nav-item dropdown full-width position-static">
<button class="btn btn-secondary dropdown-toggle" type="button" id="navbar-season" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-haspopup="true" aria-expanded="false">
Jan - Dec
</button>
<div class="dropdown-menu w-100 ms-auto position-absolute end-0" aria-labelledby="navbar-season">
<div class="dropdown-item"><div id="season-slider" class="mx-3"></div></div>
</div>
</li>
</ul>
</nav>
</div>
<script>(async() => {
const options = {
// Map
map: {
zoom: 3, // -2 - 24 // earth: 0 | Large islands: 4 | Large roads: 10
center: [-87.46, 16.76],
projection: 'mercator', // 'globe'
style: "mapbox://styles/mapbox/outdoors-v12",
clusterRadius: 40,
},
// Controls
controls: {
monthFormat: 'short', // 'long'
speciesSelectPlaceholder: 'Filter Animals',
speciesSelectDisplayLabels: true,
},
// Symbols
icons: {
map: { // number in px
size: 50,
padding: 5,
},
selection: { // css values in px, em, ...
height: '1.5rem',
width: '3rem', // variable max-width
padding: '0.5rem',
},
result: { // Icons in dropdown menu
height: '1.5rem',
width: '3rem', // fixed width to keep results indentation
padding: '0.5rem',
showCategoryIcon: false,
},
extension: "svg",
opacityInterpolateFunction: // https://easings.net/
// function steps(x) {
// switch(true) {
// case (x < 0.1): return 0.3;
// case (x <= 0.5): return 0.8;
// }
// return 1;
// }
function easeOutCubic(x) {
return Math.max(1 - Math.pow(1 - x, 3), 0.3); // leave a minimum opacity of 0.3
}
// function easeOutExpo(x) {
// // keep high opacity longer than cubic
// return Math.max(x === 1 ? 1 : 1 - Math.pow(2, -10 * x), 0.3); // leave a minimum opacity of 0.3
// }
},
// Scaling
scaling: {
shrinkFactor: 0.2, // 0-1 higher value => smaller clusters
interpolateFunction: // https://easings.net/
function easeInOutSine(x) {
return -(Math.cos(Math.PI * x) - 1) / 2;
}
// function easeInOutQuad(x) {
// return x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2;
// },
,
zoomFactor: 0.7, // 0-1 minimum scale at max zoom - smaller value => smaller symbols when zooming out
},
// Popup & temp chart
popup: {
template: (links, props) => [
$('<strong>').text(props.title),
$('<p>').text(props.description),
$('<canvas>'), // canvas for chart
$(links.map(link => $('<a>', {href: link[1]}).text(link[0])))
.join($('<span>').text(', ')),
// .join($('<br>')), // line break instead of comma
],
chart: {
data: {
labels: [...Array(12)].map((_,i) => i+1), // 1-12
// labels: [...Array(12)].map((_,i) => Intl.DateTimeFormat('en', { month: 'short' }).format(new Date(0, i))), // Short month names
// use {month: 'narrow'} for capital first letter E.g. J F M A..
datasets: [
{
type: 'line',
label: 'Water Temp',
// fill: true,
borderColor: 'rgb(75, 192, 192)',
// backgroundColor is needed to fill the legend box/circle
backgroundColor: 'rgb(75, 192, 192)',
tension: 0.2
},
{
type: 'line',
label: 'Ambient Temp',
// fill: true,
borderColor: 'rgb(255, 19, 19)',
backgroundColor: '#FF1313',
tension: 0.2
},
]
},
options: {
width: 280,
aspectRatio: 1, // 1.6,
// maintainAspectRatio: true,
plugins: {
drawSeasonalSpecies: {
dividerLine: {
color: 'rgba(75, 192, 192, 0.7)',
width: 0.5
},
},
legend: {
// https://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration
labels: {
usePointStyle: true,
boxHeight: 5,
boxWidth: 5,
}
},
title: {
// https://www.chartjs.org/docs/latest/configuration/title.html
// lower the aspectRatio if you display a title
display: true,
text: 'Seasonality',
padding: {
top: 5,
bottom: 5
}
},
tooltip: {
callbacks: {
title: context => context[0].dataset.label + " in " + Intl.DateTimeFormat('en', { month: 'long' }).format(new Date(0, context[0].parsed.x)),
label: context => {
const formattedLabel = yAxis => context.chart.scales[yAxis].options.ticks.callback(context.parsed.y);
return /*context.dataset.label + ': ' + */formattedLabel('celsius') + " / " + formattedLabel('fahrenheit');
}
}
},
},
scales: {
// https://www.chartjs.org/docs/latest/axes/#common-options-to-all-axes
x: {
ticks: {
// https://www.chartjs.org/docs/latest/axes/cartesian/_common_ticks.html
autoSkip: false, // always show all months
maxRotation: 0, // disable label rotation
minRotation: 0
}
},
celsius: {
min: -20,
suggestedMax: 40,
ticks: {
stepSize: 10,
callback: label =>
(label < 0) ? '' : `${label}°C`,
},
},
fahrenheit: {
display: true,
position: 'right',
ticks: {
callback: label =>
(label < 0) ? '' : `${Math.round((label * (9 / 5)) + 32)}°F`,
},
}
}
}
},
},
}
const filterGroup = document.getElementById('filter-group');
const locationTypes = {
swim: 1<<0, //0b001,
freedive: 1<<1, //0b010,
scuba: 1<<2, //0b100
};
mapboxgl.accessToken = 'pk.eyJ1IjoiZnJlZWRpdmluZ3Nwb3QiLCJhIjoiY2xlczZiYTZrMTQyODQzdGtwdzVmbmw4byJ9.L0sofXNziO4YiaNS7go0Fw';
const map = new mapboxgl.Map({...{container: 'map'}, ...options.map});
// prefetch the geojson while map is loading
responsePromise = fetch('spots.json')
.then(response => response.json())
.then(responseJson => responseJson)
.catch(error => console.error(error));
await map.once('load');
places = await responsePromise;
let seasonMask = 0xFFFFFF;
function applySeasonStyle(el, season) {
function _bitCount (n) {
n = n - ((n >> 1) & 0x55555555)
n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}
// bit arithmetic is beautiful and fast
// 2 bits: high season, 1: low season, 0: off season
const quotient = _bitCount(season & seasonMask) / // only sum bits of selected range
(_bitCount(seasonMask)>>1); // divide by sum of mask bits divided by 2 (bits per month)
el.style.opacity = options.icons.opacityInterpolateFunction(quotient/2);
return el;
}
( function installSlider(map) {
const slider = document.getElementById('season-slider');
noUiSlider.create(slider, {
start: [0, 11],
connect: true,
range: {
'min': 0,
'max': 11
},
behaviour: "unconstrained-invert-connects",
step: 1,
});
slider.noUiSlider.on('update', function (values) {
const month = (monthIndex, format = options.controls.monthFormat) =>
Intl.DateTimeFormat('en', { month: format }).format(new Date(0, monthIndex ^ 0));
let mask = 0;
let i = parseInt(values[0]);
const end = parseInt(values[1]);
while (true) {
mask |= 3<<(i<<1);
if (i == end) {
break;
}
i = ++i % 12;
}
seasonMask = mask;
map.triggerRepaint();
if(values[0] == values[1]) {
// display the full month name if it's only one
$('#navbar-season').text(month(values[0], 'long'));
} else {
//$('#navbar-season').text(month(values[0]) + ' - ' + month(values[1]));
$('#navbar-season').text(values.map(m => month(m)).join(' - '));
}
});
} )(map); // installSlider(map)
const speciesData = [];
const sourceId = 'spots';
for (const [i, {properties}] of places.features.entries()) {
properties.speciesId = escapeId(properties.species);
properties.id = i;
for(const [type, flag] of Object.entries(locationTypes)) {
if(properties['location-type'] & flag) {
properties[type] = true;
}
}
}
map.addSource(sourceId, {
'type': 'geojson',
'data': places,
'cluster': true,
'clusterRadius': options.map.clusterRadius,
});
const source = map.getSource(sourceId);
const Filter = new class {
constructor() {
this.speciesFilter = ["any"]
}
_update() {
source.workerOptions.filter =
(this.speciesFilter.length > 1) ? this.speciesFilter : ''
// waiting for source.setFilter to get merged: https://github.com/mapbox/mapbox-gl-js/issues/10722
source._updateWorkerData();
}
species(species, set) {
this.speciesFilter.remove(f => Array.isArray(f) ? f[2] == species : false);
if (set) {
this.speciesFilter.push(['==', ['get', 'speciesId'], species]);
}
this._update();
}
}();
for (const [category, species] of Object.entries(places.bbox.species)) {
speciesData.push({
id: escapeId(category),
text: category,
children: species.map(s => ({
id: escapeId(s),
text: s
}))
});
}
( function addSpeciesFilter(data) {
$.fn.select2.defaults.set( "theme", "bootstrap-5" );
$('#species-filter').select2({
data: speciesData,
tags: false,
templateSelection: (data, $selection) => {
// this gets appended to the select2-selection__choice__display container
// appending the text to another span so that only the img is clickable
if(options.controls.speciesSelectDisplayLabels) {
$selection.append(
$('<span>').addClass('select2-selection__choice__text').text(data.text)
);
}
return $('<img>', {
src: `assets/${data.id}.${options.icons.extension}`,
alt: data.text
}).css({
height: options.icons.selection.height,
maxWidth: options.icons.selection.width,
margin: `0 ${options.icons.selection.padding}`
});
},
escapeMarkup: $, // disable html escaping for templates by just calling the jquery constructor
selectionAdapterDecorators: [class {
selectionContainer() {
// choice__remove has to be a direct child of selection__choice to bind the right data on click
return $('<li>').append($('<span>').addClass(["select2-selection__choice__remove", "select2-selection__choice__display"]));
};
_resizeSelection() {
const $rendered = this.$selection.find('.select2-selection__rendered');
const oldWidth = $rendered.outerWidth(false);
$rendered.children().remove('.select2-selection__more');
const $children = $rendered.children();
if($children.length) {
$children.show(); // reset for window size changes
const $first = $children.eq(0);
const firstTop = $first.offset().top;
const $wrappedChildren = $children.filter((_, element) => $(element).offset().top != firstTop);
if($wrappedChildren.length) {
$wrappedChildren.hide();
const $more = $('<li>').addClass('select2-selection__more')
.append($('<span>').text('...'))
.css('padding-top', $first.css("padding-top"))
.css('padding-top', '+=1'); // adding 1px from the missing border
$rendered.append($more);
while ($more.offset().top != firstTop) {
// $more didn't fit in the first row, so we have to hide the last element
$children.filter(':visible:last').hide();
}
}
if(oldWidth != $rendered.outerWidth(false)) {
$(window).trigger(this.resizeEvent); // trigger resize dropdown
}
}
}
resizeSearch(decorated) {
// always show it with full length in second row
this.$search.css('width', '100%');
};
bind(decorated, container, $container) {
this.$selection.on('click', evt => {
if(
// don't toggle dropdown when removing options
$(evt.target).parent().hasClass('select2-selection__choice__remove') ||
// don't close when clicking into search field
(evt.target == this.$search[0] && container.isOpen())
) {
evt.stopImmediatePropagation();
}
});
decorated.call(this, container, $container);
this.resizeEvent = 'resize.select2.' + container.id;
container.on('open', () => {
this.$search.css('max-width', ''); // we want 100% width for search
this.$searchContainer.show();
this.$search.trigger('focus');
});
container.on('close', () => {
const $rendered = this.$searchContainer.prev();
if($rendered[0].hasChildNodes()) {
// only show for placeholder
this.$searchContainer.hide();
} else {
this._shrinkToPlaceholder();
}
});
}
update(decorated, data) {
decorated.call(this, data);
if(data.length) {
this._resizeSelection();
this.$selection.find('.select2-selection__choice__remove').each((_,e,$e=$(e)) => {
const title = 'Remove '+$e.parent().attr('title');
$e.attr('title', title).attr('aria-label', title);
});
} else {
this.$searchContainer.show();
}
}
_shrinkToPlaceholder() {
// this is a hacky way to calculate the min textarea size based on placeholder
// in the future with more browser support this can be done by field-sizing: content;
this.$placeholder.show();
this.$search.css('max-width', this.$placeholder.outerWidth(false) + 'px');
this.$placeholder.hide();
}
position(decorated, $selection, $container) {
decorated.call(this, $selection, $container);
this._shrinkToPlaceholder();
};
render(decorated) {
const $rendered = decorated.call(this);
const placeholder = this.options.get('placeholder');
if(placeholder) {
this.$placeholder = $('<div>', {'aria-hidden': "true"})
.text(placeholder)
.css({
height: 0,
visibility: 'hidden',
display: 'inline-block'
})
.hide();
this.$searchContainer.append(this.$placeholder);
}
const resizeSelection = this._resizeSelection.bind(this);
const throttledResizeSelection = throttle(resizeSelection, 100);
observeWidth(document.body, (width, oldWidth) => {
if(oldWidth < width) {
throttledResizeSelection();
}
});
observeWidth($rendered[0], (width, oldWidth) => {
if(oldWidth > width) {
resizeSelection();
}
});
return $rendered;
}}],
templateResult: (result, $container) => (!options.icons.result.showCategoryIcon && result.children)
? $('<span>').text(result.text).css('margin-left', options.icons.result.padding)
: $('<div>')
.append(
$('<img>', {
src: `assets/${result.id}.${options.icons.extension}`
})
.css({
height: options.icons.result.height,
width: options.icons.result.width,
marginRight: options.icons.result.padding
})
.addClass('select2-results__image')
)
.append($('<span>').text(result.text))
,
resultsAdapterDecorators: [class {
showLoading() {}
bind(decorated, container, $container) {
decorated.call(this, container, $container);
observeWidth(this.$results[0], width => {
$container.css({
minWidth: (width) ? container.$dropdown.outerWidth(false) + 'px' : ''
});
});
}
}],
selectableOptgroup: true,
dropdownAutoWidth: true,
groupResults: true,
closeOnSelect: false,
width: null,
containerCssClass: ':all:',
placeholder: options.controls.speciesSelectPlaceholder,
minimumResultsForSearch: 0,
multiple: true,
theme: 'bootstrap-5'
})
.on('select2:select select2:unselect', e => {
const {id, selected} = e.params.data;
Filter.species(id, selected);
});
})(speciesData);
class clusterOffsets {
static staticConstructor = (() => {
clusterOffsets.scales = [];
clusterOffsets.offsets = [];
clusterOffsets.centers = [];
for(let i = 0; i < 7; i++) {
// Math.PI / 3 means 3 circles per semicircle
// so we can display a total of 6 markers in a full circle + 1 in the center
clusterOffsets.offsets[i] = {
x: (i) ? Math.cos(i * Math.PI / 3) : 0,
y: (i) ? Math.sin(i * Math.PI / 3) : 0
};
const x = clusterOffsets.offsets.map(pt => pt.x);
const y = clusterOffsets.offsets.map(pt => pt.y);
const max = {x: Math.max(...x), y: Math.max(...y)};
const min = {x: Math.min(...x), y: Math.min(...y)};
// scale = 1 / (max distance + size of 1 icon)
clusterOffsets.scales[i] = 1 / (1 + Math.max(
max.x - min.x,
max.y - min.y,
));
clusterOffsets.centers[i] = {
x: (min.x + max.x) / 2,
y: (min.y + max.y) / 2
};
}
})()
constructor(radius, count, scale = 1, shrinkFactor = 0) {
this.radius = radius;
this.count = count-1; // between 1 and 7
this.scaleFactor = scale * (1 - (1 - clusterOffsets.scales[this.count]) * shrinkFactor);
}
get(index) {
return [
this.scaleFactor * this.radius * (clusterOffsets.offsets[index].x - clusterOffsets.centers[this.count].x),
this.scaleFactor * this.radius * (clusterOffsets.offsets[index].y - clusterOffsets.centers[this.count].y)
];
}
scale = () => this.scaleFactor;
}
const markers = {};
let markersOnScreen = {};
async function updateMarkers() {
const newMarkers = {};
const features = map.querySourceFeatures(sourceId);
function createPopup(props, img) {
// querySourceFeatures stringifies objects/arrays, but getClusterLeaves doesn't
const parsePropertyObject = obj => (typeof obj === 'string') ? JSON.parse(obj) : obj;
const links = parsePropertyObject(props.links);
const $template = $('<div>', {style: `width: ${options.popup.chart.options.width}px;`})
.append(options.popup.template(links, props));
const drawSeasonalSpecies = {
id: 'drawSeasonalSpecies',
beforeDatasetsDraw: (chart, _, opts) => {
const {
ctx,
chartArea: {
top,
bottom,
left,
right
},
scales: {
x,
celsius: y
}
} = chart;
const gridBox = {
top: y.getPixelForTick(1),
bottom: y.getPixelForTick(0),
left: x.getPixelForTick(0),
right: x.getPixelForTick(1),
};
gridBox.width = gridBox.right - gridBox.left;
gridBox.height = gridBox.bottom - gridBox.top;
gridBox.minSide = Math.min(gridBox.width, gridBox.height);
function drawSpecies(x, y) {
if(img) {
ctx.drawImage(img,
x*gridBox.width + gridBox.left - gridBox.minSide/2,
-y*gridBox.height + gridBox.top + gridBox.height/2 - gridBox.minSide/2,
gridBox.minSide, gridBox.minSide);
}
}
for(i = 0; i<12; i++) {
const monthActive = opts.season>>(i<<1)&3;
if (monthActive&1) drawSpecies(i,0);
if (monthActive&2) drawSpecies(i,1);
}
const color = opts.dividerLine.color || 'black';
const width = opts.dividerLine.width || 1;
ctx.beginPath();
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.moveTo(left, y.getPixelForValue(0));
ctx.lineTo(right, y.getPixelForValue(0));
ctx.stroke();
}
}
const $canvas = $template.find('canvas');
const chartOptions = {
plugins: [drawSeasonalSpecies],
type: 'bar', // 1 gridbox for each month
options: {
plugins: {
drawSeasonalSpecies: {
season: props.season,
}
},
scales: {
x: {
grid: {
offset: true, // offset grid to have the months centered to each gridbox
},
},
fahrenheit: {
display: false,
afterDataLimits: axis => {
const y = axis.chart.scales.celsius;
y.determineDataLimits(); // update y.min/max
axis.min = y.min;
axis.max = y.max;
axis.options.ticks.stepSize = y.options.ticks.stepSize;
},
}
}
}
}
$.extend(true, chartOptions, options.popup.chart);
// $.extend puts fahrenheit as first (and default) scale for datasets, so we have to force yAxisID = 'celsius'
chartOptions.data.datasets[0].yAxisID = chartOptions.data.datasets[1].yAxisID = 'celsius';
const {water, ambient} = parsePropertyObject(props.temps);
chartOptions.data.datasets[0].data = water;
chartOptions.data.datasets[1].data = ambient;
new Chart($canvas[0], chartOptions);
return new mapboxgl.Popup({maxWidth: 'none'}).setDOMContent($template[0]);
}
function getClusterLeaves(cluster_id, limit, offset) {
return new Promise((resolve, reject) => {
source.getClusterLeaves(cluster_id, limit, offset, (err, features) => {
// when source filter is updated, old clusters remain for 1 render cycle and throw errors that we have to ignore
if (err) resolve([]);
else resolve(features);
});
});
};
function addMarker(props, coords, scale = 1, offset = [0, 0]) {
const id = props.id;
let marker = markers[id];
if (!marker) {
const el = new Image();
el.dataset.season = props.season; // you can use custom data if you have assigned it in the GeoJSON data
el.dataset.species = id;
applySeasonStyle(el, props.season);
const imgPromise = new Promise(resolve => {
el.onload = el.onerror = resolve;
el.src = `./assets/${props.speciesId}.${options.icons.extension}`;
});
// mapbox keeps overriding opacity, so we have to put the img in a div to modify opacity
const div = document.createElement('div');
div.appendChild(el);
marker = markers[id] = new mapboxgl.Marker({
element: div
});
imgPromise.then(e => marker.setPopup(createPopup(props, (e.type == 'error') ? null : e.target)));
// add popup
}
const el = marker
.setLngLat(coords)
.setOffset(offset)
.getElement().firstChild;
el.style.width = el.style.height = `${scale * options.icons.map.size}px`;
applySeasonStyle(el, props.season);
if (!markersOnScreen[props.id]) {
marker.addTo(map);
}
return (newMarkers[id] = marker);
}
// min zoom can be negative
const zoomFactor = (map.getZoom() - map.getMinZoom()) / (map.getMaxZoom() - map.getMinZoom());
const zoomScale = options.scaling.interpolateFunction(zoomFactor);
const mapScale = options.scaling.zoomFactor + (1-options.scaling.zoomFactor)*zoomScale;
// clusterOffsets scales all cluster symbols to fit inside
// we want to negate this effect when zoomed in
const shrinkFactor = options.scaling.shrinkFactor * (1 - mapScale);
// for every cluster on the screen, create an HTML marker for it (if we didn't yet),
// and add it to the map if it's not there already
for (const feature of features) {
const coords = feature.geometry.coordinates;
const props = feature.properties;
if (!props.cluster) {
// reset marker offset and scale if it was in a cluster before
addMarker(props, coords);
continue;
}
// only query max 7 features
const clusterFeatures = await getClusterLeaves(props.cluster_id, 7, 0);
if(!clusterFeatures) continue;
const offsets = new clusterOffsets(options.icons.map.size + options.icons.map.padding, clusterFeatures.length, mapScale, shrinkFactor);
for(const [i, {properties}] of clusterFeatures.entries()) {
const off = offsets.get(i);
addMarker(properties, coords, offsets.scale(), offsets.get(i));
}
}
// for every marker we've added previously, remove those that are no longer visible
for (const id in markersOnScreen) {
if (!newMarkers[id]) {
markersOnScreen[id].remove();
}
}
markersOnScreen = newMarkers;
}
map.on('render', () => {
updateMarkers();
});
const layerId = 'symbols';
map.addLayer({
'id': layerId,
'type': 'symbol',
'source': sourceId,
'layout': {
'icon-allow-overlap': true,
},
});
// Change the cursor to a pointer when the mouse is over the markers.
map.on('mouseenter', layerId, () => {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', layerId, () => {
map.getCanvas().style.cursor = '';
});
})();
</script>
</body>
</html>