-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
654 lines (557 loc) · 16.4 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
<!doctype html>
<html>
<head>
<title>Flood it!</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
<link rel="stylesheet" href="lib/styledLayerControl/styledLayerControl.css">
<link rel="stylesheet" href="lib/leaflet-slider/leaflet-slider.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>
<script src="https://cdn.rawgit.com/leaflet-extras/leaflet-providers/1.1.7/leaflet-providers.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>-->
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="lib/styledLayerControl.js"></script>
<script src="lib/leaflet-slider/leaflet-slider.js"></script>
<script src="lib/covjson-reader.src.js"></script>
<script>
c3 = {}
</script>
<script src="lib/leaflet-coverage.src.js"></script>
<script>
var map = L.map('map', {
// initial center and zoom has to be set before layers can be added
center: [-13.8868043, 34.5410842],
zoom: 7,
maxZoom: 15
})
L.control.scale().addTo(map);
var baseLayerLabels = {
'Hydda.Base': 'Hydda',
'OpenStreetMap': 'OpenStreetMap',
'OpenStreetMap.BlackAndWhite': 'OpenStreetMap (B/W)',
'OpenTopoMap': 'OpenTopoMap',
'MapQuestOpen.Aerial': 'MapQuestOpen Aerial'
}
var baseLayers = {}
for (var id in baseLayerLabels) {
var layer = L.tileLayer.provider(id)
baseLayers[baseLayerLabels[id]] = layer
}
var currentBaseLayer = baseLayers[baseLayerLabels['MapQuestOpen.Aerial']]
currentBaseLayer.addTo(map)
for (var dayspast=0; dayspast <= 3; dayspast++) {
var modis_template =
"//map1{s}.vis.earthdata.nasa.gov/wmts-webmerc/" +
"{layer}/default/{time}/{tileMatrixSet}/{z}/{y}/{x}.jpg";
var date = new Date()
date.setUTCDate(date.getUTCDate() - dayspast)
var modis = L.tileLayer(modis_template, {
layer: "MODIS_Terra_CorrectedReflectance_TrueColor",
tileMatrixSet: "GoogleMapsCompatible_Level9",
maxZoom: 10,
maxNativeZoom: 9,
time: date.toISOString().split("T")[0], // YYYY-MM-DD
tileSize: 256,
subdomains: "abc",
noWrap: true,
continuousWorld: true,
// Prevent Leaflet from retrieving non-existent tiles on the
// borders.
bounds: [
[-85.0511287776, -179.999999975],
[85.0511287776, 179.999999975]
],
attribution:
"<a href='https://wiki.earthdata.nasa.gov/display/GIBS'>" +
"NASA EOSDIS GIBS</a>"
});
if (dayspast === 0) {
date = 'Today'
} else if (dayspast === 1) {
date = 'Yesterday'
} else {
date = date.toISOString().split("T")[0]
}
baseLayers['MODIS Terra: ' + date] = modis
}
var baseMaps = [{
groupName: 'Base Maps',
expanded: true,
layers: baseLayers
}]
var sumalhege = L.tileLayer.wms("http://www.globalfloods.eu/proxy/?srv=ows", {
layers: 'sumALHEGE',
format: 'image/png',
time: '2016-01-01T00:00:00',
transparent: true,
version: '1.3.0',
attribution: "Globalfloods.eu"
});
var overlays = [{
groupName : "Overlays",
expanded : true,
layers : {
"5 Year Return Period Exceedance" : sumalhege
}
}]
var layerControl = L.Control.styledLayerControl(baseMaps, overlays, {
container_width : "300px",
container_maxHeight : "500px",
collapsed: false
})
map.addControl(layerControl)
map.on('click', function (e) {
var buffer = 0.13
var pos = e.latlng
var southwest = L.latLng(pos.lat-buffer, pos.lng-buffer)
var northeast = L.latLng(pos.lat+buffer, pos.lng+buffer)
// the bbox to use for our flooding simulation
// for this area we will load DEM data
var bbox = L.latLngBounds(southwest, northeast)
console.log(bbox)
loadDEM(bbox)
})
map.on('baselayerchange', function(e) {
currentBaseLayer = e.layer
})
map.on('zoomend', function() {
if (map.getZoom() > 9) {
map.removeLayer(currentBaseLayer)
map.addLayer(baseLayers['OpenStreetMap'])
}
})
var LayerFactory = L.coverage.LayerFactory()
var paramKey = 'Band1'
var blue = L.coverage.palette.directPalette(['blue'])
var rainbow = L.coverage.palette.linearPalette(['#0000FF', '#00FFFF', '#00FF00', '#FFFF00', '#FF0000'])
var tilesize = 512
var floodLayer = null
var threshSlider = null
var chart = null
function getTally (ensemble_discharge, levs2, levs5, levs20) {
var levs20_tally = 0;
var levs5_tally = 0;
var levs2_tally = 0;
var no_lev_tally = 0;
for ( var i = 0; i < ensemble_discharge.length; i++ ) {
console.log(ensemble_discharge[i]);
if (ensemble_discharge[i] > levs20) {
levs20_tally += 1 ;
} else if (ensemble_discharge[i] > levs5) {
levs5_tally += 1 ;
} else if (ensemble_discharge[i] > levs2) {
levs2_tally += 1 ;
} else {
no_lev_tally += 1;
};
};
var res = {
levs20: levs20_tally,
levs5: levs5_tally,
levs2: levs2_tally,
no: no_lev_tally
}
console.log('levs2:',levs2);
console.log('levs5:',levs5);
console.log('levs20:',levs20);
console.log('ensemble:', ensemble_discharge)
console.log(res)
return res
}
function tallyColor(tallys){
var no = tallys.no
var two = tallys.levs2
var five = tallys.levs5
var twenty = tallys.levs20
var largest = Math.max(no, two, five, twenty);
if (no == largest) {
return "#00FF00";
} else if (two == largest) {
return "#FFFF00";
} else if (five == largest) {
return "#FF0000";
} else if (twenty == largest) {
return "#a75df0";
}
};
function displayNoDataAvail() {
var control = L.control({
position: 'topleft'
})
control.onAdd = function (map) {
var el = L.DomUtil.create('div', 'charty info');
el.innerHTML = 'No river data found, no return level chart available'
return el
}
control.addTo(map)
chart = control
}
var alertmsg = null
function removeMsg() {
if (alertmsg) {
map.removeControl(alertmsg)
alertmsg = null
}
}
function displayMsg(msg) {
var control = L.control({
position: 'topleft'
})
control.onAdd = function (map) {
var el = L.DomUtil.create('div', 'info');
el.innerHTML = msg
return el
}
control.addTo(map)
alertmsg = control
}
function displayChart(tallys) {
var control = L.control({
position: 'topleft'
})
var no = tallys.no
var two = tallys.levs2
var five = tallys.levs5
var twenty = tallys.levs20
control.onAdd = function (map) {
var el = L.DomUtil.create('div', 'charty');
var chart = new CanvasJS.Chart(el, {
height:100,
axisY:{
tickLength: 5,
tickThickness: 2,
labelFontSize: 15,
minimum:0,
maximum:51,
gridThickness:0,
title:"ensemble members",
titleFontSize:15,
},
axisX:{
tickLength: 0,
minimum:-10,
maximum:10,
valueFormatString: " ", // massive hack!
prefix: "",
},
dataPointWidth: 100,
data: [
{
type: "stackedBar",
color: "#00FF00",
toolTipContent: "{name}: {y}",
dataPoints: [
{ y: no , name: "no threshold exceeded"}
]
},
{
type: "stackedBar",
color: "#FFFF00",
dataPointMaxWidth: 50,
toolTipContent: "{name}: {y}",
dataPoints: [
{ y: two, name: "max 2-year return exceeded"}
]
},
{
type: "stackedBar",
color: "#FF0000",
dataPointMaxWidth: 50,
toolTipContent: "{name}: {y}",
dataPoints: [
{ y: five, name: "max 5-year return exceeded"}
]
},
{
type: "stackedBar",
color: "#a75df0",
dataPointMaxWidth: 50,
toolTipContent: "{name}: {y}",
dataPoints: [
{ y: twenty, name: "20-year return exceeded" }
]
}
]
});
chart.render();
L.DomEvent.disableClickPropagation(el);
return el
}
control.addTo(map)
chart = control
}
function removeChart() {
if (chart) {
map.removeControl(chart)
chart = null
}
}
function removeStuff(dontRemoveChart) {
if (threshSlider) {
map.removeControl(threshSlider)
threshSlider = null
}
if (floodLayer) {
map.removeLayer(floodLayer)
floodLayer = null
}
if (!dontRemoveChart) {
removeChart()
}
}
var floodColor = null
function loadDEM (bbox) {
removeMsg()
floodColor = null
var pos = bbox.getCenter()
console.log(pos)
displayBboxGlofas(pos)
var rlevel = 2
var time = null
fetchGlofasData (pos, time, rlevel).then(function () {
var lonWest = bbox.getWest()
var lonEast = bbox.getEast()
var latSouth = bbox.getSouth()
var latNorth = bbox.getNorth()
CovJSON.read("http://localhost:8080/wms?FORMAT=application/prs.coverage+json&TRANSPARENT=TRUE&STYLES=default-scalar%2Fdefault&LAYERS=dem2%2FBand1&COLORSCALERANGE=0%2C100&NUMCOLORBANDS=250&ABOVEMAXCOLOR=0x000000&BELOWMINCOLOR=0x000000&BGCOLOR=transparent&LOGSCALE=false&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&SRS=EPSG%3A4326&BBOX=" + lonWest + "," + latSouth + "," + lonEast + "," + latNorth +"&WIDTH=" + tilesize +"&HEIGHT=" + tilesize)
.then(function(cov) {
if (cov.coverages) {
cov = cov.coverages[0]
}
cov.loadRange(paramKey).then(function (range) {
var min = range.validMin
var max = range.validMax
if (min === -Infinity) { // FIXME should return null (covjson-reader)
displayMsg('No DEM data available')
removeStuff(true)
return
}
if (min === max) {
displayMsg('Flat topography detected, no flood simulation available')
removeStuff(true)
return
}
var thresholds = logslider(min, max)
console.log(min, max, thresholds)
if (threshSlider) {
map.removeControl(threshSlider)
}
var firstCall = true
threshSlider = new L.Control.Slider(function(value) {
var threshold = thresholds[parseInt(value)]
var newcov = applyThreshold(cov, threshold)
if (floodLayer) {
map.removeLayer(floodLayer)
}
floodLayer = LayerFactory(newcov, {
keys: [paramKey],
palette: floodColor ? L.coverage.palette.directPalette([floodColor]) : blue
}).on('add', function () {
if (firstCall) {
map.fitBounds(floodLayer.getBounds(), {
maxZoom: 9
})
firstCall = false
}
})
floodLayer.setZIndex(10)
floodLayer.addTo(map)
}, {
orientation:'vertical',
id: 'slider',
logo: 'F',
size: '250px',
collapsed: false,
value: 1,
min: 0,
max: 9,
syncSlider: true,
getValue: function(i) {
return thresholds[i] + 'm'
}
})
threshSlider.addTo(map)
})
// debug output
/*
var layer = LayerFactory(cov, {
keys: [paramKey],
palette: rainbow
})
layer.setZIndex(10)
layer.addTo(map);
*/
})
})
}
function fetchRlevel (lat, lon, rlevel) {
// return level (statistical x-year discharge)
return fetch('http://incubator.ecmwf.int/2e/rasdaman/ows?service=WCS&version=2.0.1&request=ProcessCoverages&query=for c in (return_level'+rlevel+') return encode(c[Lat('+lat+'), Long('+lon+')], "csv")')
.then(function (result) {
return result.text().then(function(data) {
data = data.substr(1, data.length-2)
if (data === '-9999') {
// we're done here
return null
}
var rlevel_discharge = parseFloat(data)
return rlevel_discharge
})
})
}
function fetchDischarge (lat, lon, time) {
var time = '2016-01-01T00:00:00+00:00'
return fetch( 'http://incubator.ecmwf.int/2e/rasdaman/ows?service=WCS&version=2.0.1&request=ProcessCoverages&query=for c in (discharge_forecast) return encode(c[Lat('+lat+'), Long('+lon+'), ansi("' + time +'"), forecast(120), ensemble(0:51)], "csv")')
.then(function (result) {
return result.text().then(function(data) {
console.log('discharge:', data)
data = data.substr(1, data.length-2)
var ensemble_discharge = data.split(',').map(parseFloat)
return ensemble_discharge
})
})
}
function fetchGlofasData (pos, time, rlevel) {
var lat = pos.lat
var lon = pos.lng
removeChart()
return fetchRlevel(lat, lon, 2).then(function (dis2) {
if (dis2 === null) {
displayNoDataAvail()
return
}
var proms = [
fetchDischarge(lat, lon, time),
fetchRlevel(lat, lon, 5),
fetchRlevel(lat, lon, 20)
]
return Promise.all(proms).then(function (res) {
var ensemble_discharge = res[0]
var dis5 = res[1]
var dis20 = res[2]
var tallys = getTally (ensemble_discharge, dis2, dis5, dis20)
displayChart(tallys)
floodColor = tallyColor(tallys)
})
})
}
var waterVal = 0
function applyThreshold (cov, threshold) {
var rangeWrapper = function (domain, range) {
var newrange = shallowcopy(range)
newrange.get = function (obj) {
var val = range.get({x: obj.x, y: obj.y})
if (val !== null && val < threshold) {
return waterVal // random constant value = water
} else {
return null // no water
}
}
newrange.dataType = 'integer'
return newrange
}
var loadRange = function(key) {
return Promise.all([cov.loadDomain(), cov.loadRange(key)])
.then(function (result) {
var domain = result[0]
var range = result[1]
return rangeWrapper(domain, range)
})
}
var newcov = shallowcopy(cov)
newcov.loadRange = loadRange
newcov.loadRanges = null
newcov.subsetByIndex = function () {
// need to override this as well, otherwise it uses original data
// we don't subset anyway, so this is fine
return Promise.resolve(newcov)
}
newcov.parameters = new Map()
newcov.parameters.set(paramKey, {
key: paramKey,
observedProperty: {
categories: [{
id: 'water'
}]
},
categoryEncoding: new Map([['water', [waterVal]]])
})
return newcov
}
var bboxPoly = null
function displayBboxGlofas (pos) {
//return
if (bboxPoly) {
map.removeLayer(bboxPoly)
}
coordinates = getBoundingBoxGlofas( pos.lat, pos.lng );
var poly = [
[ coordinates[2], coordinates[3] ],
[ coordinates[4], coordinates[5] ],
[ coordinates[6], coordinates[7] ],
[ coordinates[8], coordinates[9] ],
[ coordinates[2], coordinates[3] ]
]
console.log('poly', poly)
bboxPoly = L.polygon(poly, { fillOpacity: 0 } ).addTo(map);
}
function getBoundingBoxGlofas(lat, lon) {
// Compute the GloFAS pixel bounding box for a specific lat/lon var coordinates = new Array(10);
// c_Lat, c_Lon,
// ulc_lat, ulc_Lon
// urc_lat, urc_Lon
// llc_lat, llc_Lon
// lrc_lat, lrc_Lon // c_Lat
var coordinates = []
coordinates[0] = Math.floor( lat * 10 ) / 10 + 0.05;
// c_Lon
coordinates[1] = Math.floor( lon * 10 ) / 10 + 0.05; // ulc_lat
coordinates[2] = coordinates[0] + 0.05;
// urc_lat
coordinates[4] = coordinates[0] + 0.05;
// llc_lat
coordinates[6] = coordinates[0] - 0.05;
// lrc_lat
coordinates[8] = coordinates[0] - 0.05; // ulc_lon
coordinates[3] = coordinates[1] + 0.05;
// urc_lon
coordinates[5] = coordinates[1] - 0.05;
// llc_lon
coordinates[7] = coordinates[1] - 0.05;
// lrc_lon
coordinates[9] = coordinates[1] + 0.05;
return coordinates;
}
function logslider( min, max ) {
// The result should be between:
// minv, maxv
var minv = Math.log( min );
var range = max - min;
var maxv = Math.log( min + ( range / 2 ) );
var step = range / 10 // calculate adjustment factor
var scale = (maxv-minv) / (max-min);
var position = min;
var slider = [];
for ( i = 0; i < 10; i++) {
slider.push(Math.ceil(Math.exp(minv + scale*(position-min))));
position = position + step;
}
return slider;
}
function shallowcopy (obj) {
if (obj instanceof Map) {
copy = new Map(obj)
} else {
copy = Object.create(Object.getPrototypeOf(obj))
for (var prop in obj) {
copy[prop] = obj[prop]
}
}
return copy
}
</script>
</body>
</html>