-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathswe.js
361 lines (297 loc) · 12.1 KB
/
swe.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
function parse_date_string(str) {
var y = str.substr(0,4),
m = str.substr(4,2) - 1,
d = str.substr(6,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
var map, layercontrol;
function loadMap() {
// Get selected dates from datepicker
var selectedDates = document.getElementById('datepicker').value.split(',');
// Get the Leaflet map container
// removed default zoom control
map = L.map("map", { zoomControl: false }).setView([0, 0], 2);
var basemaps = {
Topography: L.tileLayer.wms('http://ows.mundialis.de/services/service?', {
layers: 'TOPO-WMS'
}),
Places: L.tileLayer.wms('http://ows.mundialis.de/services/service?', {
layers: 'OSM-WMS'
}),
'SatelliteImagery': L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/'+
'/tile/{z}/{y}/{x}', {
attribution: 'Esri',
maxZoom: 19
}),
};
basemaps.SatelliteImagery.addTo(map);
// Add layer control to the map
layercontrol = L.control.layers(basemaps).addTo(map);
// Add zoom control to the top right corner
L.control.zoom({ position: 'topright' }).addTo(map);
var usaBounds = [
// -125, 30, -78, 51
[30, -125.000000], // Southwest
[51, -78] // Northeast
];
// Fit the map to the bounding box
map.fitBounds(usaBounds);
fetch('us-states.json')
.then(response => response.json())
.then(data => {
fetch('state-abbreviation.json')
.then(response => response.json())
.then(stateAbbreviations => {
var stateNameMarkers = L.layerGroup();
var stateLayer = L.geoJSON(data, {
style: function (feature) {
return {
color: '#000000',
weight: 1
};
},
onEachFeature: function (feature, layer) {
if (feature.properties && feature.properties.name) {
var stateName = feature.properties.name;
var abbreviation = stateAbbreviations[stateName] || stateName;
var center = layer.getBounds().getCenter();
var marker = L.marker(center, {
icon: L.divIcon({
className: 'state-label',
html: `<strong>${stateName}</strong>`,
iconSize: [100, 40]
})
}).addTo(stateNameMarkers);
function updateLabelContent() {
const zoomLevel = map.getZoom();
const label = zoomLevel >= 4 ? stateName : abbreviation;
const isZoomedOut = zoomLevel < 3;
marker.setIcon(L.divIcon({
className: 'state-label',
html: `<strong>${label}</strong>`,
iconSize: [100, 40]
}));
if (isZoomedOut) {
marker.remove();
} else {
if (!map.hasLayer(marker)) {
marker.addTo(stateNameMarkers);
}
}
}
map.on('zoomend', updateLabelContent);
updateLabelContent();
}
}
}).addTo(map);
stateLayer.bringToFront();
stateNameMarkers.addTo(map);
layercontrol.addOverlay(stateLayer, "State Boundaries");
layercontrol.addOverlay(stateNameMarkers, "State Names");
layercontrol.addOverlay(wmslayer, "Predicted SWE " + date);
})
.catch(error => {
console.error('Error loading abbreviations:', error);
});
})
.catch(error => {
console.error('Error loading GeoJSON data:', error);
});
// Event listener for map clicks
map.on('click', function(e) {
var lat = e.latlng.lat.toFixed(6);
var lon = e.latlng.lng.toFixed(6);
var content = `<strong>Coordinates:</strong><br>Latitude: ${lat}<br>Longitude: ${lon}<br><button onclick="copyCoordinates('${lat}', '${lon}')">Copy Coordinates</button>`;
L.popup()
.setLatLng(e.latlng)
.setContent(content)
.openOn(map);
});
}
// Function to copy coordinates to clipboard
function copyCoordinates(lat, lon) {
const textToCopy = `${lat}, ${lon}`;
if (navigator.clipboard) {
navigator.clipboard.writeText(textToCopy)
.then(() => {
alert('Coordinates copied to clipboard!');
})
.catch(err => {
console.error('Failed to copy: ', err);
});
} else {
// Fallback for older browsers
var tempInput = document.createElement('input');
tempInput.value = textToCopy;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
alert('Coordinates copied to clipboard!');
}
}
function add_swe_predicted_geotiff(date){
// URL to your GeoTIFF file
var wmslayer = L.tileLayer.wms('http://geobrain.csiss.gmu.edu/cgi-bin/mapserv?'+
'map=/var/www/html/swe_forecasting/map/swe_predicted_'+date+'.tif.map&', {
layers: 'swemap',
format: 'image/png',
transparent: true
});
wmslayer.addTo(map);
layercontrol.addOverlay(wmslayer, "Predicted SWE "+date);
}
function setup_datepicker(dateArray){
$('#datepicker').datepicker({
format: 'yyyy-mm-dd',
todayHighlight: true,
timeZone: 'America/Los_Angeles',
autoclose: true,
beforeShowDay: function(date) {
// Convert date to yyyy-mm-dd format
var formattedDate = date.getFullYear() + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
// Check if the date is in the dateArray
return dateArray.includes(formattedDate);
}
}).on('show', function(e) {
// Ensure the datepicker is properly positioned
var datepicker = $('.datepicker');
var offset = $(this).offset();
datepicker.css({
top: offset.top + $(this).outerHeight(),
left: offset.left
});
});
}
// Function to find the latest date
function findLatestDate(dates) {
if (dates.length === 0) {
return null; // Return null for an empty array
}
// Use reduce to find the maximum date
var latestDate = dates.reduce(function (maxDate, currentDate) {
maxDateObject = new Date(maxDate)
currentDateObject = new Date(currentDate)
return currentDateObject > maxDateObject ? currentDate : maxDate;
});
return latestDate;
}
function refresh_calendar(){
// Fetch the CSV file
fetch('../swe_forecasting/date_list.csv', {
method: 'GET',
cache: 'no-store', // 'no-store' disables caching
})
.then(response => response.text())
.then(data => {
console.log(data)
// Parse CSV data and convert the date column into an array
Papa.parse(data, {
header: true,
complete: function(results) {
// Assuming 'date' is the name of your date column
var dateArray = results.data.map(function(row) {
return row.date;
});
console.log("dateArray = " + dateArray)
// Initialize Bootstrap Datepicker with the dateArray
setup_datepicker(dateArray)
// found the latest date and show on the map
var latestdate = findLatestDate(dateArray)
console.log("Found latest date is " + latestdate)
$('#datepicker').datepicker('setDate', new Date(latestdate));
add_swe_predicted_geotiff(latestdate)
}
});
})
.catch(error => console.error('Error fetching CSV file:', error));
}
function add_listener_to_buttons(){
// Button click listener
$('#load_swe_to_map').on('click', function() {
// Get the selected date from the datepicker
var selectedDate = $('#datepicker').datepicker('getFormattedDate');
console.log("loading layer for "+ selectedDate)
// Show overlay with selected date
add_swe_predicted_geotiff(selectedDate);
});
// Close overlay button click listener
$('#download_swe_geotiff').on('click', function() {
// Create a temporary anchor element
var selectedDate = $('#datepicker').datepicker('getFormattedDate');
console.log("downloading geotiff for "+ selectedDate)
// Open a new window to initiate the download
window.open("../swe_forecasting/output/swe_predicted_"+selectedDate+".tif", '_blank');
});
}
function getColor(d) {
// Specify the number of classes (baskets)
// var numClasses = 10;
// // Generate grades dynamically based on the number of classes
// var grades = Array.from({ length: numClasses + 1 }, function (_, index) {
// return (30 / numClasses) * index;
// });
// // Define color scale from gray to blue to purple
// var colorScale = chroma.scale(['#f0f0f0', '#4d4dff', '#9900cc']).mode('lab').colors(numClasses);
// //
// // Find the appropriate color class based on the input value
// for (var i = 0; i < grades.length - 1; i++) {
// if (d >= grades[i] && d < grades[i + 1]) {
// return colorScale[i];
// }
// }
// console.log(colorScale)
// Define color classes
// var colors = ['#f0f0f0', '#d6caf5', '#b9a6f9', '#9782fc', '#6c5efe',
// '#5b48f9', '#713eee', '#8131e2', '#8e21d7', '#9900cc']
var colors = ['#003366', '#336699', '#6699CC', '#99CCFF', '#99FFFF',
'#CCFFFF', '#FFFFCC', '#FFFF99', '#FFFF66', '#FFFF33']
// Specify the number of classes (baskets)
var numClasses = 10;
// Generate grades dynamically based on the number of classes
var grades = Array.from({ length: numClasses + 1 }, function (_, index) {
return (30 / numClasses) * index;
});
// Find the appropriate color class based on the input value
for (var i = 0; i < grades.length - 1; i++) {
if (d >= grades[i] && d < grades[i + 1]) {
return colors[i];
}
}
// Handle the case where the input value is greater than the last grade
return colors[grades.length - 1];
}
function add_legend(){
// Your MapServer configuration with 15 classes
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
labels = [];
div.style.backgroundColor = 'white';
div.style.padding = '10px';
// Specify the number of classes (baskets)
var numClasses = 10;
// Generate grades dynamically based on the number of classes
var grades = Array.from({ length: numClasses + 1 }, function(_, index) {
return (30 / numClasses) * index;
});
// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
div.innerHTML +=
'<i style="background:' + getColor(grades[i] + 1) + '"></i> ' +
grades[i] + (grades[i + 1] ? '–' + grades[i + 1] + '<br>' : '+');
}
return div;
};
legend.addTo(map);
}
// Automatically load the map when the document is ready
document.addEventListener('DOMContentLoaded', function() {
loadMap();
refresh_calendar()
add_listener_to_buttons()
add_legend()
});