-
Notifications
You must be signed in to change notification settings - Fork 35
/
Supercluster.vue
825 lines (692 loc) · 24.1 KB
/
Supercluster.vue
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
<template>
<div class="h100">
<!-- The map & data -->
<div
id="openlittermap"
ref="openlittermap"
/>
<SearchCustomTags />
<!-- Websockets -->
<LiveEvents
@fly-to-location="updateUrlPhotoIdAndFlyToLocation"
/>
</div>
</template>
<script>
import LiveEvents from '../../components/LiveEvents.vue';
import SearchCustomTags from "../../components/global/SearchCustomTags.vue";
import {
CLUSTER_ZOOM_THRESHOLD,
MAX_ZOOM,
MEDIUM_CLUSTER_SIZE,
LARGE_CLUSTER_SIZE,
MIN_ZOOM,
ZOOM_STEP
} from '../../constants';
import L from 'leaflet';
import './SmoothWheelZoom.js';
// Todo - fix this export bug (The request of a dependency is an expression...)
import glify from 'leaflet.glify';
import { mapHelper } from '../../maps/mapHelpers';
import dropdown from './select-dropdown';
var map;
var clusters;
var merchants;
var litterArtPoints;
var points;
var prevZoom = MIN_ZOOM;
var cleanups;
var userId = null;
var pointsLayerController;
var globalLayerController;
var pointsControllerShowing = false;
var globalControllerShowing = false;
const green_dot = L.icon({
iconUrl: '/images/vendor/leaflet/dist/dot.png',
iconSize: [10, 10]
});
const grey_dot = L.icon({
iconUrl: '/images/vendor/leaflet/dist/grey-dot.jpg',
iconSize: [13, 10]
});
/**
* Create the point to display for each piece of Litter Art
*/
function createArtIcon (feature, latlng)
{
const x = [latlng.lng, latlng.lat];
return (feature.properties.verified === 2)
? L.marker(x, { icon: green_dot })
: L.marker(x, { icon: grey_dot });
}
/**
* Icon to use for displaying Cleanups
*/
function createCleanupIcon (feature, latlng)
{
return L.marker(latlng, { icon: green_dot });
}
/**
* Create the cluster or point icon to display for each feature
*/
function createClusterIcon (feature, latlng)
{
if (!feature.properties.cluster)
{
return (feature.properties.verified === 2)
? L.marker(latlng, { icon: green_dot })
: L.marker(latlng, { icon: grey_dot });
}
const count = feature.properties.point_count;
const size = (count < MEDIUM_CLUSTER_SIZE)
? 'small'
: count < LARGE_CLUSTER_SIZE
? 'medium'
: 'large';
const icon = L.divIcon({
html: '<div class="mi"><span class="ma">' + feature.properties.point_count_abbreviated + '</span></div>',
className: 'marker-cluster-' + size,
iconSize: L.point(40, 40)
});
return L.marker(latlng, { icon });
}
/**
* Layer controller when below ZOOM_CLUSTER_THRESHOLD
*/
function createGlobalGroups ()
{
if (pointsControllerShowing)
{
map.removeControl(pointsLayerController);
pointsControllerShowing = false;
}
if (!globalControllerShowing)
{
globalLayerController = L.control.layers(null, null).addTo(map);
globalLayerController.addOverlay(clusters, 'Global');
globalLayerController.addOverlay(litterArtPoints, 'Litter Art');
if (cleanups) {
globalLayerController.addOverlay(cleanups, 'Cleanups');
}
if (merchants) {
globalLayerController.addOverlay(merchants, 'Merchants');
}
globalControllerShowing = true;
}
}
/**
* Layer Controller when above ZOOM_CLUSTER_THRESHOLD
*/
function createPointGroups ()
{
if (globalControllerShowing)
{
map.removeControl(globalLayerController)
globalControllerShowing = false;
}
if (!pointsControllerShowing)
{
const overlays = {
Alcohol: new L.LayerGroup(),
Brands: new L.LayerGroup(),
Coastal: new L.LayerGroup(),
Coffee: new L.LayerGroup(),
Dumping: new L.LayerGroup(),
Food: new L.LayerGroup(),
Industrial: new L.LayerGroup(),
Other: new L.LayerGroup(),
PetSurprise: new L.LayerGroup(),
Sanitary: new L.LayerGroup(),
Smoking: new L.LayerGroup(),
SoftDrinks: new L.LayerGroup(),
};
pointsLayerController = L.control.layers(null, overlays).addTo(map);
pointsControllerShowing = true;
}
}
/**
* Zoom to a cluster when it is clicked
*/
function onEachFeature (feature, layer)
{
if (feature.properties.cluster)
{
layer.on('click', function (e)
{
const zoomTo = ((map.getZoom() + ZOOM_STEP) > MAX_ZOOM)
? MAX_ZOOM
: (map.getZoom() + ZOOM_STEP);
map.flyTo(e.latlng, zoomTo, {
animate: true,
duration: 2
});
});
}
}
/**
* On each art point...
*
* Todo: Smooth zoom to that piece
*/
function onEachArtFeature (feature, layer)
{
layer.on('click', function (e)
{
map.flyTo(feature.geometry.coordinates, 14, {
animate: true,
duration: 10
});
const url = new URL(window.location.href);
url.searchParams.set('lat', feature.geometry.coordinates[0]);
url.searchParams.set('lon', feature.geometry.coordinates[1]);
url.searchParams.set('zoom', CLUSTER_ZOOM_THRESHOLD);
url.searchParams.set('photo', feature.properties.photo_id);
L.popup(mapHelper.popupOptions)
.setLatLng(feature.geometry.coordinates)
.setContent(mapHelper.getMapImagePopupContent(feature.properties, url.toString()))
.openOn(map);
});
}
/**
* On each cleanup in this.$store.state.cleanups.geojson.features
*/
function onEachCleanup (feature, layer)
{
layer.on('click', function (e)
{
const latLng = [feature.geometry.coordinates[1], feature.geometry.coordinates[0]];
map.flyTo(latLng, 14, {
animate: true,
duration: 10
});
const content = mapHelper.getCleanupContent(feature.properties, userId);
L.popup(mapHelper.popupOptions)
.setLatLng(latLng)
.setContent(content)
.openOn(map);
});
}
/**
* On each cleanup in this.$store.state.cleanups.geojson.features
*/
function onEachMerchant (feature, layer)
{
layer.on('click', function (e)
{
const latLng = [feature.geometry.coordinates[1], feature.geometry.coordinates[0]];
map.flyTo(latLng, 14, {
animate: true,
duration: 10
});
const content = mapHelper.getMerchantContent(feature.properties, userId);
L.popup(mapHelper.popupOptions)
.setLatLng(latLng)
.setContent(content)
.openOn(map);
// Initialize Swiper
const mySwiper = new Swiper('.swiper-container', {
navigation: {
prevEl: '#prevButton',
nextEl: '#nextButton',
},
});
});
}
/**
* Get any active layers
*
* @return layers|null
*/
function getActiveLayers ()
{
let layers = [];
// This is not ideal but it works as the indexes are in the same order
pointsLayerController._layerControlInputs.forEach((lyr, index) => {
if (lyr.checked)
{
// temp fix to rename petsurprise from map to the dogshit table
const name = (pointsLayerController._layers[index].name.toLowerCase() === 'petsurprise')
? 'dogshit'
: pointsLayerController._layers[index].name.toLowerCase();
layers.push(name);
}
});
return (layers.length > 0)
? layers
: null;
}
export default {
name: 'Supercluster',
components: {
SearchCustomTags,
LiveEvents
},
props: {
'activeLayer': {
default: 'clusters',
required: false
}
},
data () {
return {
visiblePoints: []
}
},
mounted () {
/** 0: Hack! Bind variable outside of vue scope */
window.olm_map = this;
/** 1. Create map object */
map = L.map('openlittermap', {
center: [0, 0],
zoom: MIN_ZOOM,
scrollWheelZoom: false,
smoothWheelZoom: true,
smoothSensitivity: 2
});
map.scrollWheelZoom = true;
this.flyToLocationFromURL();
const date = new Date();
const year = date.getFullYear();
/** 2. Add tiles, attribution, set limits */
const mapLink = '<a href="https://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © ' + mapLink + ' & Contributors',
maxZoom: MAX_ZOOM,
minZoom: MIN_ZOOM
}).addTo(map);
map.attributionControl.addAttribution('Litter data © OpenLitterMap & Contributors ' + year + ' Clustering @ MapBox');
// Clusters
clusters = L.geoJSON(null, {
pointToLayer: createClusterIcon,
onEachFeature: onEachFeature,
})
if (this.$store.state.globalmap.geojson?.features) {
clusters.addData(this.$store.state.globalmap.geojson.features);
}
if (this.activeLayer === "clusters") {
clusters.addTo(map);
}
// Art
litterArtPoints = L.geoJSON(null, {
pointToLayer: createArtIcon,
onEachFeature: onEachArtFeature
});
if (this.$store.state.globalmap?.artData?.features) {
litterArtPoints.addData(this.$store.state.globalmap.artData.features);
}
// Cleanups
if (this.$store.state.cleanups.geojson)
{
cleanups = L.geoJSON(this.$store.state.cleanups.geojson, {
onEachFeature: onEachCleanup,
pointToLayer: createCleanupIcon
});
}
// When we are viewing Cleanups and the map is clicked,
// We want to extract the coordinates
if (this.activeLayer === "cleanups")
{
cleanups.addTo(map);
map.on('click', function(e) {
const lat = e.latlng.lat;
const lng = e.latlng.lng;
window.olm_map.$store.commit('setCleanupLocation', {
lat,
lng
});
});
if (this.$route.params.hasOwnProperty('invite_link'))
{
const cleanup = this.$store.state.cleanups.cleanup;
const latLng = [cleanup.lat, cleanup.lon];
map.flyTo(latLng, 16, {
animate: true,
duration: 5
});
const userId = (this.$store.state.user.auth)
? this.$store.state.user.user.id
: null;
L.popup(mapHelper.popupOptions)
.setLatLng(latLng)
.setContent(mapHelper.getCleanupContent(cleanup, userId))
.openOn(map);
}
}
// For Cleanups, we need to know if the current userId has joined a cleanup
if (this.$store.state.user.auth) {
userId = this.$store.state.user.user.id;
}
// Merchants
if (Object.keys(this.$store.state.merchants.geojson).length > 0)
{
merchants = L.geoJSON(this.$store.state.merchants.geojson, {
onEachFeature: onEachMerchant,
pointToLayer: createCleanupIcon
});
}
// When we are viewing Cleanups and the map is clicked,
// We want to extract the coordinates
if (this.activeLayer === "merchants")
{
merchants.addTo(map);
map.on('click', function(e) {
const lat = e.latlng.lat;
const lng = e.latlng.lng;
window.olm_map.$store.commit('setMerchantLocation', {
lat,
lng
});
});
}
// For Cleanups, we need to know if the current userId has joined a cleanup
if (this.$store.state.user.auth) {
userId = this.$store.state.user.user.id;
}
map.on('moveend', this.update);
createGlobalGroups();
map.on('overlayadd', this.update);
map.on('overlayremove', this.update);
map.on('popupopen', mapHelper.scrollPopupToBottom);
map.on('popupclose', () => {
const url = new URL(window.location.href);
url.searchParams.delete('photo');
window.history.pushState(null, '', url);
});
map.on('zoom', () => {
if (points?.remove) {
points.remove();
}
});
this.setupYearDropdown();
},
methods: {
/**
* The user dragged or zoomed the map, or changed a category
*/
async update ()
{
this.updateLocationInURL();
const bounds = map.getBounds();
const bbox = {
'left': bounds.getWest(),
'bottom': bounds.getSouth(),
'right': bounds.getEast(),
'top': bounds.getNorth()
};
const zoom = Math.round(map.getZoom());
// We don't want to make a request at zoom level 2-5 if the user is just panning the map.
// At these levels, we just load all global data for now
if (zoom === 2 && zoom === prevZoom) return;
if (zoom === 3 && zoom === prevZoom) return;
if (zoom === 4 && zoom === prevZoom) return;
if (zoom === 5 && zoom === prevZoom) return;
// Remove points when zooming out
if (points)
{
clusters.clearLayers();
points.remove();
}
// Get the year from url
const searchParams = new URLSearchParams(window.location.search);
const year = parseInt(searchParams.get('year')) || null;
const fromDate = searchParams.get('fromDate') || null;
const toDate = searchParams.get('toDate') || null;
const username = searchParams.get('username') || null;
// Get Clusters or Points
if (zoom < CLUSTER_ZOOM_THRESHOLD)
{
createGlobalGroups();
// Remove photo id and filters from the url when zooming out
const url = new URL(window.location.href);
url.searchParams.delete('fromDate');
url.searchParams.delete('toDate');
url.searchParams.delete('username');
url.searchParams.delete('photo');
window.history.pushState(null, '', url);
await axios.get('/global/clusters', {
params: {
zoom,
bbox,
year
}
})
.then(response => {
console.log('get_clusters.update', response);
clusters.clearLayers();
clusters.addData(response.data);
})
.catch(error => {
console.error('get_clusters.update', error);
});
}
else
{
createPointGroups()
const layers = getActiveLayers();
await axios.get('/global/points', {
params: {
zoom,
bbox,
layers,
year,
fromDate,
toDate,
username
}
})
.then(response => {
console.log('get_global_points', response);
this.visiblePoints = response.data.features;
// Clear layer if prev layer is cluster.
if (prevZoom < CLUSTER_ZOOM_THRESHOLD)
{
clusters.clearLayers();
}
const data = response.data.features.map(feature => {
return [feature.geometry.coordinates[0], feature.geometry.coordinates[1]];
});
// New way using webGL
points = glify.points({
map,
data,
size: 10,
color: { r: 0.054, g: 0.819, b: 0.27, a: 1 }, // 14, 209, 69 / 255
click: (e, point, xy) => {
const feature = response.data.features.find(f => {
return f.geometry.coordinates[0] === point[0]
&& f.geometry.coordinates[1] === point[1];
});
if (!feature) {
return;
}
// Set the photo id in the url when opening a photo
const url = new URL(window.location.href);
url.searchParams.set('photo', feature.properties.photo_id);
window.history.pushState(null, '', url);
return this.renderLeafletPopup(feature, e.latlng)
},
});
// If there is a photo id in the url, open it
let urlParams = new URLSearchParams(window.location.search);
let photoId = parseInt(urlParams.get('photo'));
if (photoId) {
if (!this.visiblePoints.length) return;
const feature = this.visiblePoints.find(f => f.properties.photo_id === photoId);
if (feature) {
this.renderLeafletPopup(
feature,
[feature.geometry.coordinates[0], feature.geometry.coordinates[1]]
)
}
}
})
.catch(error => {
console.error('get_global_points', error);
});
}
prevZoom = zoom;
},
/**
* Helper method to create a Popup
*
* @param feature
* @param latLng
*/
renderLeafletPopup (feature, latLng)
{
const url = new URL(window.location.href);
url.searchParams.set('lat', feature.geometry.coordinates[0]);
url.searchParams.set('lon', feature.geometry.coordinates[1]);
url.searchParams.set('zoom', CLUSTER_ZOOM_THRESHOLD);
url.searchParams.set('photo', feature.properties.photo_id);
L.popup(mapHelper.popupOptions)
.setLatLng(latLng)
.setContent(mapHelper.getMapImagePopupContent(feature.properties, url.toString()))
.openOn(map);
},
/**
* Goes to the location and zoom given in the URL
* Params are: lat, lon, zoom, photo
*/
flyToLocationFromURL ()
{
let urlParams = new URLSearchParams(window.location.search);
let latitude = parseFloat(urlParams.get('lat') || 0);
let longitude = parseFloat(urlParams.get('lon') || 0);
let zoom = parseFloat(urlParams.get('zoom') || MIN_ZOOM);
let photoId = parseInt(urlParams.get('photo'));
// Validate lat, lon, and zoom level
latitude = (latitude < -85 || latitude > 85) ? 0 : latitude;
longitude = (longitude < -180 || longitude > 180) ? 0 : longitude;
zoom = (zoom < 2 || zoom > MAX_ZOOM) ? MIN_ZOOM : zoom;
if (latitude === 0 && longitude === 0 && zoom === 2) return;
this.flyToLocation({latitude, longitude, zoom, photoId});
},
/**
* Updates the url with the photoId
* and goes to the location
*/
updateUrlPhotoIdAndFlyToLocation (location)
{
const zoom = Math.round(map.getZoom());
const url = new URL(window.location.href);
url.searchParams.set('photo', location.photoId);
window.history.pushState(null, '', url);
const flyDistanceInMeters = map.distance(
map.getCenter(),
[location.latitude, location.longitude]
)
// If we're viewing points and moving within 2km
if (zoom >= CLUSTER_ZOOM_THRESHOLD && flyDistanceInMeters <= 2000) {
this.flyToLocation({...location, duration: 1});
} else {
this.flyToLocation(location);
}
},
/**
* Goes to the location provided
*/
flyToLocation (location)
{
const latLng = L.latLng(location.latitude, location.longitude);
const zoom = location.photoId && Math.round(location.zoom) < CLUSTER_ZOOM_THRESHOLD
? CLUSTER_ZOOM_THRESHOLD
: location.zoom;
// Calculate the offset in pixels to position the point 10% from the bottom
const mapSize = map.getSize();
const point = map.project(latLng, zoom);
const offsetY = mapSize.y * 0.4; // 0.4 times the map height
const targetPoint = point.subtract([0, offsetY]);
const targetLatLng = map.unproject(targetPoint, zoom);
map.flyTo(targetLatLng, zoom, {
animate: true,
duration: location.duration ?? 5,
});
},
/**
* Simply updates the URL
* with the current map location and zoom
*/
updateLocationInURL ()
{
const location = map.getCenter();
const url = new URL(window.location.href);
url.searchParams.set('lat', location.lat);
url.searchParams.set('lon', location.lng);
url.searchParams.set('zoom', map.getZoom());
window.history.pushState(null, '', url);
},
/**
* Initializes the dropdown to select
* the year for which to show clusters, and points
*/
setupYearDropdown ()
{
dropdown.initialize();
let years = [
{label: 'All Time', value: '*'}
];
for (let y = new Date().getFullYear(); y >= 2017; y--)
{
years.push({label: y.toString(), value: y.toString()});
}
let selectedYear = parseInt((new URLSearchParams(window.location.search)).get('year')) || '*';
L.control.select({
position: 'topleft',
selectedDefault: selectedYear.toString(),
items: years,
onSelect: (function (year)
{
const url = new URL(window.location.href);
if (year === '*')
{
url.searchParams.delete('year');
}
else
{
url.searchParams.set('year', year);
}
// reload the site
window.history.pushState(null, '', url);
window.location.reload();
})
}).addTo(map);
}
}
};
</script>
<style lang="scss" src="./select-dropdown.scss"></style>
<style>
@import 'leaflet/dist/leaflet.css';
#openlittermap {
height: 100%;
margin: 0;
position: relative;
}
.leaflet-marker-icon {
border-radius: 20px;
}
.mi {
height: 100%;
margin: auto;
display: flex;
justify-content: center;
border-radius: 20px;
}
.leaflet-control {
pointer-events: visiblePainted !important;
}
.leaflet-cleanup-container {
padding: 1em 2em;
}
.leaflet-cleanup-container p {
margin: 10px 0 !important;
}
.updated-by-admin {
margin-top: 5px !important;
margin-bottom: 0 !important;
margin-right: 2em;
font-size: 13px !important;
font-style: italic !important;
}
</style>