-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.js
634 lines (520 loc) · 19.4 KB
/
base.js
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
import { map, icon, Marker } from 'leaflet';
import 'leaflet-control-geocoder';
import './geoip.js';
import './marker/control.js';
import { layerSets, layers } from './layers/sets.js';
import tweets from './tweets.js';
import url from './url.js';
import twitter from './twitter.js';
import controls from './controls.js';
import 'leaflet-control-window';
import 'leaflet-draw';
import 'jquery';
import 'leaflet-easybutton';
import './scripts/leaflet.magnifyingglass.js';
import 'leaflet-minimap';
let GeoJSON = require('geojson');
// Find better solution soon
const iconRetinaUrl = '../../../static/leaflet/dist/images/marker-icon-2x.png';
const iconUrl = '../../../static/leaflet/dist/images/marker-icon.png';
const shadowUrl = '../../../static/leaflet/dist/images/marker-shadow.png';
const iconDefault = icon({
iconRetinaUrl,
iconUrl,
shadowUrl,
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
tooltipAnchor: [16, -28],
shadowSize: [41, 41]
});
Marker.prototype.options.icon = iconDefault;
let defaultState = {
zoom: 3,
center: {
lat: 22,
lng: 0,
},
layers: [
'light',
'energy',
'manufacturing',
'fossil-fuel-operations',
//'power-plants',
'no2_2021_test',
'tweets'
],
}
let defaultOptions = {
zoomControl: false,
tap: true,
maxZoom: 19,
touchZoom: 'center',
//drawControl: true
}
let popupoptions = {maxWidth : 700}
L.Circle.include({
contains: function (latLng) {
return this.getLatLng().distanceTo(latLng) < this.getRadius();
}
});
let tweetBoxActive = false;
let radius_zoom = [1,1,1,1,2.5,4,5.5,7.5,9.8,12.5,15.4,19,23,27.2,32,37.2,40,40,40,40,40];
let base = {
map: null,
slowFlyTo: true,
layerSets: {},
layers: {},
externalJSON: false,
pushState: false,
stateArray: [],
validJsonUrl: false,
magnifyingGlass: null,
country_n: 4,
editableLayers: new L.FeatureGroup(),
init: function() {
// init leaflet map
base.map = map('map', {
...defaultOptions,
});
tweets.init();
tweets.loadMarkers();
twitter.init();
base.addEventHandlers();
base.layerSets = layerSets;
base.layers = layers;
base.setInitialState();
},
getState: function() {
return {
center: base.map.getCenter(),
zoom: base.map.getZoom(),
layers: base.getVisibleLayers(),
tweet: tweets.activeTweet,
polygons: tweets.data.polygons
}
},
radius_zoom: function() {
return radius_zoom
},
setInitialState: function() {
base.map.setView(defaultState.center, defaultState.zoom);
let state = url.getState();
if (!state.center){
state.center = defaultState.center
}
base.setState({...defaultState, ...state});
let tweet = state.tweet;
$(tweets).on("loaded", function() {
if (!state.tweet) {
let path = url.getPath()
if (path in tweets.data.pathToTweetId)
tweet = tweets.data.pathToTweetId[path];
}
if (tweet)
tweets.show(tweet);
});
base.addControls();
controls.addControls();
// let miniMap = new L.Control.MiniMap(layerSets.baseTiles.layers.satellite_minimap, {
// position: "topleft",
// zoomLevelOffset: 0,
// toggleDisplay: true,
// minimized: true,
// width: 400,
// height: 490,
// }).addTo(base.map);
// var map = L.map('map', {
// center: [0, 0],
// zoom: 5,
// layers: [ "satellite" ]
// });
// if(!base.magnifyingGlass){
// base.magnifyingGlass = L.magnifyingGlass({
// layers: [ layerSets.baseTiles.layers.dark, layerSets.points.layers['power-plants'], layerSets.overlays.layers['no2_2021'] ],
// radius: 200,
// zoomOffset: 0,
// fixedPosition: false,
// latLng: state.center
// }).addTo(base.map);
// }
// L.Control.MagnifyingGlass(magnifyingGlass, {
// forceSeparateButton: true
// }).addTo(base.map);
},
setState: function(state){
base.pushState = false;
base.flyTo(state);
$(base.map).one('moveend', function () {
console.log(state.layers)
base.showLayers(state.layers);
base.pushState = true;
if(state.polygons){
tweets.data.polygons = state.polygons
base.showPolygons(state)
base.showLayer("polygons")
}
url.pushState();
base.updateCircleSize();
})
},
flyTo: function(state) {
// Only show tile layer in fly-to animation
let tileLayers = Object.keys(base.layerSets.baseTiles.layers)
let layers = state.layers.filter(x => tileLayers.includes(x))
// Keep tweets layer
if (state.layers.includes('tweets'))
layers.push('tweets')
base.showLayers(layers);
if(base.slowFlyTo){
base.map.flyTo(state.center, state.zoom, {noMoveStart: true});
} else {
base.map.flyTo(state.center, state.zoom, {noMoveStart: true, duration: 1});
base.slowFlyTo = true
}
},
getWindowCorrectedCenter: function(center, zoom) {
let sidebarOffset = document.querySelector('.leaflet-sidebar').getBoundingClientRect().width;
return base.map.unproject(base.map.project(center, zoom).add([sidebarOffset / 2, 0]), zoom); //substract when sidebar on the left
},
showSidebar: function(module, content = null) {
let sbs = [tweets]
sbs.forEach((m) => {
if (m != module) {
m.sidebar.hide();
}
});
module.sidebar.show();
if (content)
module.sidebar.setContent(content);
return module.sidebar;
},
showControlwindow: function(module, content = null, title = null) {
let sbs = [tweets]
sbs.forEach((m) => {
if (m != module) {
m.controlwindow.hide();
}
});
if (content){
module.controlwindow.content(content)
}
if (title){
module.controlwindow.title(title)
}
module.controlwindow.show('topRight')
return module.controlwindow;
},
showPopup: function(module, content = null) {
let sbs = [tweets]
sbs.forEach((m) => {
if (m != module) {
map.closePopup();
}
});
if (content)
L.popup(popupOptions).setContent(content)
return module.popup;
},
showLayers: function(ids) {
let visibleLayers = base.getVisibleLayers()
// Show
ids.forEach((id) => {
if(!visibleLayers.includes(id))
base.showLayer(id);
});
// Hide layers visible, but not in ids
visibleLayers.forEach((id) => {
if (!ids.includes(id))
base.hideLayer(id)
});
// Default to light tiles
if (base.layerSets.baseTiles.getVisibleLayers().length == 0)
base.map.addLayer(base.layerSets.tiles.layers['light'])
// Default to empty overlays layer
if (base.layerSets.overlays.getVisibleLayers().length == 0)
base.map.addLayer(base.layerSets.overlays.layers['empty'])
},
showLayer: function(id) {
if (!base.map.hasLayer(base.layers[id]))
base.map.addLayer(base.layers[id])
},
showPolygons: function(state) {
base.layers["polygons"].clearLayers();
let colorIterator = 0
let color_arr = ["#FFF600", "#ff7800", "#FF0008", "#0088FF"]
let data = decodeURIComponent(state.polygons);
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
if(isValidHttpUrl(data)){
base.layers["polygons"].clearLayers();
$.getJSON(data, function(json){
// add GeoJSON layer to the map once the file is loaded
let datalayer = L.geoJson(json ,{
onEachFeature: function ( feature, layer ){
layer.setStyle({
weight: 1.5,
color: color_arr[3],
opacity: 0.8,
interactive: false,
//fillColor: "#ff7800",
stroke: true,
fillOpacity: 0.1,
dashArray: ''
});
base.layers["polygons"].addLayer( layer )
}
})
//base.map.fitBounds(datalayer.getBounds());
});
base.externalJSON = true
} else {
L.geoJSON(JSON.parse(data), {
onEachFeature: function ( feature, layer ){
if(colorIterator > 3)
colorIterator = 0
layer.setStyle({
weight: 3,
color: color_arr[colorIterator],
opacity: 0.8,
interactive: false,
//fillColor: "#ff7800",
stroke: true,
fillOpacity: 0.1,
dashArray: ''
});
base.layers["polygons"].addLayer( layer )
colorIterator = colorIterator + 1
}
});
}
},
hidePolygons: function() {
base.hideLayer("polygons")
},
hideLayer: function(id) {
if (base.map.hasLayer(base.layers[id]))
base.map.removeLayer(base.layers[id])
},
getVisibleLayers: function() {
return Object.keys(this.layers).filter(k => (base.map.hasLayer(this.layers[k])));
},
updateCircleSize: function() {
function calcRadius(val, zoom) {
if(val != radius_zoom()[zoom])
return radius_zoom()[zoom]
else
return
}
base.map.eachLayer(function (marker) {
//console.log(marker)
if (marker._radius != undefined){
//console.debug(marker)
let size = null
if(marker.feature.properties.rank_world != undefined){
size = Math.max(radius_zoom[base.map.getZoom()], radius_zoom[base.map.getZoom()]*(3/Math.pow(marker.feature.properties.rank_world, 1/4)))
} else if(marker.feature.properties.population != undefined) {
size = Math.max(radius_zoom[base.map.getZoom()], radius_zoom[base.map.getZoom()]*(Math.pow(marker.feature.properties.population, 1/4)/20))
} else if(marker.feature.properties.rank != undefined) {
size = Math.max(radius_zoom[base.map.getZoom()], radius_zoom[base.map.getZoom()]*(3/Math.pow(marker.feature.properties.rank, 1/4)))
} else {
size = radius_zoom[base.map.getZoom()]
}
marker.setRadius(size)
}
});
},
addControls: function() {
let drawOptions = {
position: 'bottomleft',
draw: {
polyline: false,
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
},
shapeOptions: {
color: '#bada55'
}
},
circle: false, // Turns off this drawing tool
rectangle: false,
marker: false,
circlemarker: false,
polyline: true
},
edit: {
featureGroup: base.editableLayers,//base.layers["polygons"],//base.editableLayers, //REQUIRED!!
remove: false,
edit: false
}
};
L.control.scale({
position: 'bottomright'
}).addTo(base.map)
L.control.zoom({
position: 'bottomleft'
}).addTo(base.map);
L.Control.geocoder({
position: 'bottomleft'
}).addTo(base.map);
let shareUrlButton = L.easyButton({
states: [{
stateName: 'toggle-tweets', // name the state
icon: 'nf nf-fa-share', // and define its properties
title: 'Share Link', // like its title
onClick: function(btn, map) { // and its callback
let link = 'https://map.decarbnow.space' + url.getPath()
navigator.clipboard.writeText(link)
.then(() => {
alert('Map link copied to clipboard. Tweet this link to add the tweet to the map.');
})
.catch(err => {
alert('Error in copying URL: ', err);
});
//url.pushState();
//btn.state('fa-cleared-trash'); // change state on click!
}
}]
});
shareUrlButton.setPosition('bottomleft').addTo( base.map );
let homeButton = L.easyButton({
states: [{
stateName: 'go-home', // name the state
icon: 'nf nf-fa-home', // and define its properties
title: 'Overview', // like its title
onClick: function(btn, map) { // and its callback
//base.map.flyTo(base.getState().center, 5.0);
base.map.setView(defaultState.center, defaultState.zoom);
base.setState({...defaultState});
tweets.closeSidebar()
}
}]
});
homeButton.setPosition('bottomleft').addTo( base.map );
let removePolygonsButton = L.easyButton({
states: [{
stateName: 'fa-clear-trash', // name the state
icon: 'fa-trash', // and define its properties
title: 'Clear drawlayer', // like its title
onClick: function(btn, map) { // and its callback
if(tweets.data.polygons){
if (confirm('Are you sure you want to remove all your self-created drawings?')) {
base.layers["polygons"].clearLayers();
tweets.data.polygons = null
url.pushState();
} else {
// Do nothing!
return;
}
} else {
return;
}
//btn.state('fa-cleared-trash'); // change state on click!
}
}]
});
removePolygonsButton.setPosition('bottomleft').addTo( base.map );
let drawControl = new L.Control.Draw(drawOptions);
base.map.addControl(drawControl);
},
addEventHandlers: function() {
base.map.on(L.Draw.Event.CREATED, function (e) {
base.showLayer("polygons")
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
//Remove loaded JSON first
if(base.externalJSON){
base.layers["polygons"].clearLayers();
tweets.data.polygons = null
url.pushState();
base.externalJSON = false
}
base.layers["polygons"].addLayer(layer)
// Extract GeoJson from featureGroup
let data = layer.toGeoJSON();
// Stringify the GeoJson
if(tweets.data.polygons == null){
data = encodeURIComponent(JSON.stringify(data));
} else {
let data_old = data
data = {
"type" : "FeatureCollection",
"features": [JSON.parse(decodeURIComponent(tweets.data.polygons)), data]
}
data = encodeURIComponent(JSON.stringify(data))
}
if(data.length > 3800){
alert("Polygon string too long. You cannot add more stuff.");
} else {
tweets.data.polygons = data
tweets.addGeoJson()
}
});
base.map.on("moveend", function () {
// base.stateArray.forEach((item, i) => {
// base.showLayer(item)
// });
if (base.pushState) {
url.pushState()
}
});
base.map.on("movestart", function () {
// if(base.layerSets.tweets){
// base.stateArray = [].concat(base.layerSets.tweets.getVisibleLayers());
//
// base.stateArray.forEach((item, i) => {
// base.hideLayer(item)
// });
// }
});
base.map.on("move", function () {
//console.log(base.magnifyingGlass);
// base.magnifyingGlass = L.magnifyingGlass({
// //layers: [ layerSets.baseTiles.layers.dark, layerSets.points.layers['power-plants'], layerSets.overlays.layers['no2_2021'] ],
// //radius: 100,
// //zoomOffset: 0,
// fixedPosition: true,
// latLng: base.map.getCenter()
// });
//base.magnifyingGlass.setLatLng = base.map.getCenter()
});
base.map.on("contextmenu", function(e) {
base.tweetBoxActive = true;
tweets.closeSidebar();
base.map.flyTo(e.latlng);
twitter.showTweetBox(e);
let class_ch = document.querySelector('.crosshair')
class_ch.classList.add('hidden')
});
base.map.on("zoomend", function () {
base.updateCircleSize()
});
base.map.on("click", function (e) {
//tweets.loadStoryLines()
base.tweetBoxActive = false;
tweets.closeSidebar();
//base.slowFlyTo = false;
twitter.marker.remove();
twitter.controlwindow.hide();
});
base.map.on('baselayerchange overlayadd overlayremove', function (e) {
if (base.pushState)
url.pushState();
return true;
});
}
}
export default base