-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplanvisit.html
605 lines (550 loc) · 25.1 KB
/
planvisit.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
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags and title -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>The Best Time for Visitors to SF to Plan to Cross the Golden Gate Bridge Today</title>
<!-- External scripts and stylesheets -->
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<style>
/* CSS styles for animations, night mode, and mobile responsiveness */
@keyframes blink {
0%, 100% { opacity: 0; }
50% { opacity: 0.5; }
}
.animate-blink {
animation: blink 0.5s ease-in-out 3;
}
body.night-mode {
background-color: #1a1a1a;
color: #f0f0f0;
}
body.night-mode .bg-white {
background-color: #2a2a2a;
}
body.night-mode .border-gray-200 {
border-color: #3a3a3a;
}
body.night-mode .shadow-md {
box-shadow: 0 4px 6px -1px rgba(255, 255, 255, 0.1), 0 2px 4px -1px rgba(255, 255, 255, 0.06);
}
@media (max-width: 640px) {
#best-visit-time h3 {
font-size: 1rem;
}
#best-visit-time ul {
font-size: 0.875rem;
}
#current-weather h2 {
font-size: 1.25rem;
}
#current-weather p {
font-size: 0.875rem;
}
.mobile-title {
display: none;
}
.chart-container {
position: relative;
height: 300px; /* Adjust this value as needed */
overflow: hidden;
transform: translate3d(0,0,0);
will-change: transform;
}
.chart-legend {
position: absolute;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
background-color: rgba(255, 255, 255, 0.8);
padding: 5px;
font-size: 0.75rem;
}
.chart-legend-item {
display: flex;
align-items: center;
}
.chart-legend-color {
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 4px;
}
.mobile-hide-title {
display: none;
}
}
body {
-webkit-transform: translateZ(0);
-moz-transform: translateZ(0);
-ms-transform: translateZ(0);
-o-transform: translateZ(0);
transform: translateZ(0);
}
/* Container for the image, controls aspect ratio and cropping */
.image-container {
position: relative;
width: 100%;
padding-top: 63.75%; /* 75% * 0.85 to crop 15% of height */
overflow: hidden;
}
/* Styles for the image itself */
#ggb-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 117.65%; /* 100 / 0.85 to compensate for cropping */
object-fit: cover; /* Ensures image fills container without distortion */
object-position: center top; /* Aligns image to top, cropping from bottom */
transition: opacity 0.3s ease-in-out;
}
#ggb-image.loading {
opacity: 0.5;
}
</style>
</head>
<body class="bg-gray-100 min-h-screen">
<div class="container mx-auto px-4 py-4 sm:py-8">
<!-- Page title -->
<h1 class="text-3xl font-bold mb-6 text-center mobile-hide-title">Golden Gate Bridge Weather Forecast</h1>
<!-- Live video feed of Golden Gate Bridge -->
<div class="mb-6">
<div class="image-container rounded-lg overflow-hidden">
<img id="ggb-image" class="w-full h-full object-cover" src="https://raw.githubusercontent.com/danielraffel/ggb/main/ggb.screenshot.png" alt="Golden Gate Bridge">
</div>
</div>
<!-- Weather Chart container -->
<div class="chart-container bg-white shadow-md rounded-lg p-6 mb-6">
<h2 class="text-xl font-semibold mb-4">Today's Weather Forecast</h2>
<!-- Add this new div for the mobile legend -->
<div id="mobile-legend" class="md:hidden flex justify-around text-xs mb-2">
<div class="flex items-center">
<span class="w-3 h-3 rounded-full bg-red-400 mr-1"></span>
<span>Temp (°F)</span>
</div>
<div class="flex items-center">
<span class="w-3 h-3 rounded-full bg-blue-400 mr-1"></span>
<span>Cloud (%)</span>
</div>
<div class="flex items-center">
<span class="w-3 h-3 rounded-full bg-green-400 mr-1"></span>
<span>Wind (MPH)</span>
</div>
<div class="flex items-center">
<span class="w-3 h-3 rounded-full bg-purple-400 mr-1"></span>
<span>Precip (%)</span>
</div>
</div>
<canvas id="weatherChart"></canvas>
</div>
<!-- Best Visit Time section -->
<div id="best-visit-time" class="bg-white shadow-md rounded-lg p-6 mb-6">
<div class="flex justify-between">
<div class="w-1/2 pr-2">
<h3 class="text-xl font-semibold mb-2 text-yellow-500">
🥇 Best time <span class="mobile-title">to visit</span>
</h3>
<ul id="best-time-info-1" class="text-lg list-none p-0"></ul>
</div>
<div class="w-1/2 pl-2">
<h3 class="text-xl font-semibold mb-2 text-gray-500">
🥈 Second best <span class="mobile-title">time</span>
</h3>
<ul id="best-time-info-2" class="text-lg list-none p-0"></ul>
</div>
</div>
</div>
<!-- Current Weather section -->
<div id="current-weather" class="bg-white shadow-md rounded-lg p-6">
<h2 class="text-xl font-semibold mb-2">Current Weather</h2>
<p id="current-weather-info" class="text-lg"></p>
</div>
<!-- Error Message container -->
<div id="error-message" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mt-6 hidden" role="alert">
<strong class="font-bold">Error!</strong>
<span class="block sm:inline" id="error-text"></span>
</div>
</div>
<!-- Footer -->
<div>
<div class="text-sm sm:mt-0 mt-2 sm:mb-6 mb-0 text-center">
<a href="https://github.com/danielraffel/ggb" target="_blank" style="text-decoration: underline;">About this Site</a>
</div>
</div>
<script>
// Global variables
let weatherChart;
let chartData;
// Helper functions
function formatTime(date) {
return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
}
function isNightTime() {
const hour = new Date().getHours();
return hour < 6 || hour >= 20;
}
function applyTheme() {
// Apply night mode theme based on time of day
const body = document.body;
const isNight = isNightTime();
if (isNight) {
body.classList.add('night-mode');
} else {
body.classList.remove('night-mode');
}
}
// Fetch weather data and update chart
async function fetchWeatherData() {
try {
// Fetch data from API
const response = await axios.get('https://api.open-meteo.com/v1/forecast?latitude=37.8199&longitude=-122.4783&hourly=temperature_2m,cloudcover,windspeed_10m,precipitation_probability&timezone=America/Los_Angeles&forecast_days=1&temperature_unit=fahrenheit');
const data = response.data;
// Process and filter data
const times = data.hourly.time.map(time => new Date(time));
const temperatures = data.hourly.temperature_2m;
const cloudCover = data.hourly.cloudcover;
const windSpeed = data.hourly.windspeed_10m;
const precipProb = data.hourly.precipitation_probability;
const filteredData = times.reduce((acc, time, index) => {
const hour = time.getHours();
if (hour >= 5 && hour <= 21) { // 5am to 9pm
acc.times.push(time);
acc.temperatures.push(temperatures[index]);
acc.cloudCover.push(cloudCover[index]);
acc.windSpeed.push(windSpeed[index]);
acc.precipProb.push(precipProb[index]);
}
return acc;
}, { times: [], temperatures: [], cloudCover: [], windSpeed: [], precipProb: [] });
// Update UI components
updateWeatherChart(filteredData.times, filteredData.temperatures, filteredData.cloudCover, filteredData.windSpeed, filteredData.precipProb);
updateBestVisitTime(filteredData.times, filteredData.temperatures, filteredData.cloudCover, filteredData.windSpeed, filteredData.precipProb);
updateCurrentWeather(filteredData.times, filteredData.temperatures, filteredData.cloudCover, filteredData.windSpeed, filteredData.precipProb);
// Hide error message if it was previously shown
document.getElementById('error-message').classList.add('hidden');
} catch (error) {
console.error('Error fetching weather data:', error);
showErrorMessage('Failed to fetch weather data. Please try again later.');
}
}
function updateWeatherChart(times, temperatures, cloudCover, windSpeed, precipProb) {
// Prepare data for chart
const ctx = document.getElementById('weatherChart').getContext('2d');
const chartContainer = ctx.canvas.closest('.chart-container');
if (weatherChart) {
weatherChart.destroy();
}
const isMobile = window.innerWidth <= 640;
chartData = {
times,
temperatures,
cloudCover,
windSpeed,
precipProb
};
createChart();
}
function createChart() {
// Create and configure the weather chart using Chart.js
if (!chartData) return;
const ctx = document.getElementById('weatherChart').getContext('2d');
const isMobile = window.innerWidth <= 640;
const chartColors = {
temperature: 'rgb(255, 99, 132)',
cloudCover: 'rgb(54, 162, 235)',
windSpeed: 'rgb(75, 192, 192)',
precipProb: 'rgb(153, 102, 255)'
};
weatherChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartData.times.map(formatTime),
datasets: [
{
label: 'Temperature (°F)',
data: chartData.temperatures,
borderColor: chartColors.temperature,
backgroundColor: chartColors.temperature + '33',
yAxisID: 'y-temperature',
pointBackgroundColor: chartColors.temperature,
pointBorderColor: chartColors.temperature,
},
{
label: 'Cloud Cover (%)',
data: chartData.cloudCover,
borderColor: chartColors.cloudCover,
backgroundColor: chartColors.cloudCover + '33',
yAxisID: 'y-percentage',
pointBackgroundColor: chartColors.cloudCover,
pointBorderColor: chartColors.cloudCover,
},
{
label: 'Wind Speed (mph)',
data: chartData.windSpeed,
borderColor: chartColors.windSpeed,
backgroundColor: chartColors.windSpeed + '33',
yAxisID: 'y-wind',
pointBackgroundColor: chartColors.windSpeed,
pointBorderColor: chartColors.windSpeed,
},
{
label: 'Precipitation Probability (%)',
data: chartData.precipProb,
borderColor: chartColors.precipProb,
backgroundColor: chartColors.precipProb + '33',
yAxisID: 'y-percentage',
pointBackgroundColor: chartColors.precipProb,
pointBorderColor: chartColors.precipProb,
}
]
},
options: {
responsive: true,
maintainAspectRatio: !isMobile,
aspectRatio: 2,
plugins: {
legend: {
display: !isMobile,
labels: {
usePointStyle: true,
pointStyle: 'line',
boxWidth: 30,
boxHeight: 1,
},
},
},
layout: {
padding: {
top: 8,
right: 8,
bottom: isMobile ? 20 : 8, // Increase bottom padding on mobile
left: 8
}
},
scales: {
x: {
display: true,
title: {
display: true,
text: 'Time'
},
ticks: {
callback: function(val, index) {
const time = this.getLabelForValue(val);
if (isMobile) {
// Mobile formatting
const [hours, minutes, period] = time.split(/[:\s]/);
const hourNum = parseInt(hours);
if (hourNum === 12) {
return '12P';
} else if (period === 'PM') {
return `${hourNum}P`;
} else {
return `${hourNum}A`;
}
} else {
// Desktop formatting (unchanged)
return time;
}
},
padding: isMobile ? 8 : 0 // Add some padding to x-axis ticks on mobile
}
},
'y-temperature': {
type: 'linear',
display: true,
position: 'left',
title: {
display: true,
text: 'Temperature (°F)'
},
suggestedMax: Math.max(...chartData.temperatures) + 1 // Add just a little space above the highest temperature
},
'y-percentage': {
type: 'linear',
display: true,
position: 'right',
min: 0,
max: 100,
title: {
display: true,
text: isMobile ? 'Cloud & Precip (%)' : 'Cloud Cover & Precipitation (%)'
},
grid: {
drawOnChartArea: false,
}
},
'y-wind': {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: 'Wind Speed (mph)'
},
grid: {
drawOnChartArea: false,
},
suggestedMax: Math.max(...chartData.windSpeed) + 1 // Add just a little space above the highest wind speed
}
}
},
plugins: [{
id: 'customLegend',
afterRender: (chart) => legendCallback(chart),
}],
});
// Update mobile legend colors
const legendItems = document.querySelectorAll('#mobile-legend .rounded-full');
legendItems[0].style.backgroundColor = chartColors.temperature;
legendItems[1].style.backgroundColor = chartColors.cloudCover;
legendItems[2].style.backgroundColor = chartColors.windSpeed;
legendItems[3].style.backgroundColor = chartColors.precipProb;
}
function updateBestVisitTime(times, temperatures, cloudCover, windSpeed, precipProb) {
// Calculate and display the best times to visit
let scores = [];
for (let i = 0; i < times.length; i++) {
const hour = times[i].getHours();
if (hour >= 6 && hour <= 20) { // Only consider times between 6 AM and 8 PM
const tempScore = temperatures[i] * 2; // Prioritize warmth
const rainScore = 100 - precipProb[i]; // Higher score for lower precipitation probability
const cloudScore = (100 - cloudCover[i]) / 2; // Less weight on cloud cover
const windScore = (20 - windSpeed[i]) / 2; // Less weight on wind speed
const totalScore = tempScore + rainScore + cloudScore + windScore;
scores.push({ time: times[i], score: totalScore });
}
}
// Sort scores in descending order
scores.sort((a, b) => b.score - a.score);
// Get the top 2 times
const bestTime1 = scores[0].time;
const bestTime2 = scores[1].time;
function createInfoList(time, index) {
const i = times.indexOf(time);
return `
<li>⏰ ${formatTime(time)}</li>
<li>🌡️ ${temperatures[i].toFixed(1)}°F</li>
<li>🌧 ${precipProb[i]}% chance</li>
<li>☁️ ${cloudCover[i]}% cover</li>
<li>🌬️ ${windSpeed[i].toFixed(1)} mph</li>
`;
}
document.getElementById('best-time-info-1').innerHTML = createInfoList(bestTime1);
document.getElementById('best-time-info-2').innerHTML = createInfoList(bestTime2);
}
function updateCurrentWeather(times, temperatures, cloudCover, windSpeed, precipProb) {
// Update the current weather information
const now = new Date();
const currentIndex = times.findIndex(time => time > now) - 1;
if (currentIndex >= 0) {
const currentWeatherInfo = document.getElementById('current-weather-info');
currentWeatherInfo.innerHTML = `
<p>Temperature: ${temperatures[currentIndex]}°F</p>
<p>Cloud Cover: ${cloudCover[currentIndex]}%</p>
<p>Wind Speed: ${windSpeed[currentIndex]} mph</p>
<p>Precipitation: ${precipProb[currentIndex]}%</p>
`;
}
}
function showErrorMessage(message) {
// Display error message to the user
const errorElement = document.getElementById('error-message');
const errorTextElement = document.getElementById('error-text');
errorTextElement.textContent = message;
errorElement.classList.remove('hidden');
}
// Set up Intersection Observer for lazy loading
const observerOptions = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
createChart();
}
});
}, observerOptions);
// Start observing the chart container
const chartContainer = document.querySelector('.chart-container');
if (chartContainer) {
observer.observe(chartContainer);
}
// Initialize
applyTheme();
fetchWeatherData();
// Update theme every minute
setInterval(applyTheme, 60000);
// Update weather data every 30 minutes
setInterval(fetchWeatherData, 1800000);
// Recreate chart on window resize
window.addEventListener('resize', () => {
if (chartData) {
createChart();
}
});
// Function to update the image
async function updateGGBImage() {
const img = document.getElementById('ggb-image');
img.classList.add('loading');
try {
// Cache-busting technique 1: Use GitHub API to get the latest file content
const apiUrl = 'https://api.github.com/repos/danielraffel/ggb/contents/ggb.screenshot.png';
const apiResponse = await fetch(apiUrl, {
headers: {
'Accept': 'application/vnd.github.v3+json',
// Cache-busting technique 2: Add no-cache header to API request
'Cache-Control': 'no-cache'
}
});
const fileData = await apiResponse.json();
if (!fileData.content) {
throw new Error('No content found in the API response');
}
// Cache-busting technique 3: Decode and use the Base64 content directly
const byteCharacters = atob(fileData.content);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: 'image/png'});
// Cache-busting technique 4: Use a Blob URL
const objectURL = URL.createObjectURL(blob);
// Create a new Image object to preload the image
const tempImg = new Image();
tempImg.onload = function() {
console.log('New image loaded, updating src');
// Cache-busting technique 5: Update image src with the new Blob URL
img.src = objectURL;
URL.revokeObjectURL(img.src);
img.classList.remove('loading');
};
tempImg.onerror = function() {
console.error('Error loading new image');
img.classList.remove('loading');
};
tempImg.src = objectURL;
} catch (error) {
console.error('Error fetching image:', error);
img.classList.remove('loading');
}
}
// Cache-busting technique 6: Frequent updates
// Update the image every 30 seconds to ensure latest version
setInterval(updateGGBImage, 30 * 1000);
// Call updateGGBImage immediately after defining the image element
document.getElementById('ggb-image').onload = function() {
updateGGBImage();
};
</script>
</body>
</html>