Poniendo distintos meses en frontend del tiempo
This commit is contained in:
parent
4a241475e5
commit
7b1c076eb9
|
|
@ -248,3 +248,36 @@ footer {
|
|||
}
|
||||
|
||||
.termometro.templado { fill: #4caf50; }
|
||||
|
||||
#mes-navegacion {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.mes-btn {
|
||||
background: rgba(20, 20, 20, 0.8);
|
||||
color: var(--color-acento);
|
||||
border: 1px solid var(--color-borde);
|
||||
border-radius: 8px;
|
||||
padding: 4px 12px;
|
||||
font-size: 1.2rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-family: 'EB Garamond', serif;
|
||||
}
|
||||
|
||||
.mes-btn:hover {
|
||||
background: rgba(31, 53, 88, 0.9);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
#mes-nombre {
|
||||
font-family: 'EB Garamond', serif;
|
||||
font-size: 1.2rem;
|
||||
color: var(--color-acento);
|
||||
min-width: 80px;
|
||||
text-align: center;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,13 +12,18 @@
|
|||
<header>
|
||||
<h1>Estadísticas del Tiempo</h1>
|
||||
<h2 id="stats-location">Cargando datos…</h2>
|
||||
<div id="mes-navegacion">
|
||||
<button id="prev-month" class="mes-btn">‹</button>
|
||||
<span id="mes-nombre">Enero</span>
|
||||
<button id="next-month" class="mes-btn">›</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container">
|
||||
|
||||
<!-- ÚLTIMO DATO -->
|
||||
<article class="tarjeta">
|
||||
<h2>Ahora</h2>
|
||||
<h2>Hoy</h2>
|
||||
<p>Fecha: <strong id="last-date">--</strong></p>
|
||||
<p>Temperatura: <strong id="last-temp">--</strong></p>
|
||||
<p>Humedad: <strong id="last-humidity">--</strong></p>
|
||||
|
|
|
|||
|
|
@ -1,76 +1,67 @@
|
|||
// API URL absoluta
|
||||
const API_URL = "http://aplicacionesdevanguardia.es/eltiempo/apis/api-weather-reverse.php?ciudad=madrid";
|
||||
|
||||
/* ---------- UTILIDADES ---------- */
|
||||
// ====================
|
||||
// Helper
|
||||
// ====================
|
||||
function $(id) { return document.getElementById(id); }
|
||||
|
||||
function $(id) {
|
||||
return document.getElementById(id);
|
||||
const monthNames = ["Enero","Febrero","Marzo","Abril","Mayo","Junio",
|
||||
"Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
|
||||
|
||||
let selectedMonth = new Date().getMonth(); // mes actual
|
||||
|
||||
function updateMonthHeader() {
|
||||
$("mes-nombre").textContent = monthNames[selectedMonth];
|
||||
}
|
||||
|
||||
function monthName(monthIndex) {
|
||||
return new Date(2026, monthIndex, 1)
|
||||
.toLocaleDateString("es-ES", { month: "long" });
|
||||
}
|
||||
|
||||
/* ---------- CARGA PRINCIPAL ---------- */
|
||||
|
||||
// ====================
|
||||
// Cargar datos del JSON
|
||||
// ====================
|
||||
async function loadStats() {
|
||||
try {
|
||||
console.log("Cargando datos desde API:", API_URL);
|
||||
const res = await fetch(API_URL);
|
||||
const response = await fetch(API_URL);
|
||||
if (!response.ok) throw new Error("Error cargando datos: " + response.status);
|
||||
|
||||
if (!res.ok) throw `Error HTTP: ${res.status}`;
|
||||
const data = await response.json();
|
||||
|
||||
const data = await res.json();
|
||||
console.log("Datos recibidos:", data);
|
||||
if (!data || !data.length) throw new Error("Datos vacíos");
|
||||
|
||||
if (!data || !data.length) throw "Sin datos";
|
||||
|
||||
renderLastDay(data[0]);
|
||||
renderLastData(data);
|
||||
renderMonthStats(data);
|
||||
renderTrend(data);
|
||||
|
||||
$("stats-location").textContent = "Madrid (datos históricos)";
|
||||
} catch (e) {
|
||||
$("stats-location").textContent = "Error cargando estadísticas";
|
||||
console.error("Error en loadStats:", e);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
$("stats-location").textContent = "Error cargando datos";
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- ÚLTIMO DÍA ---------- */
|
||||
|
||||
function renderLastDay(day) {
|
||||
$("last-date").textContent = day.dia;
|
||||
$("last-temp").textContent = `${day.temp_min}°C / ${day.temp_max}°C`;
|
||||
$("last-humidity").textContent = `${Math.round(day.humedad)} %`;
|
||||
$("last-rain").textContent = `${day.lluvia} mm`;
|
||||
$("last-wind").textContent = `${Math.round(day.viento_velocidad)} km/h`;
|
||||
$("last-sunrise").textContent = day.amanecer;
|
||||
$("last-sunset").textContent = day.anochecer;
|
||||
// ====================
|
||||
// Último dato
|
||||
// ====================
|
||||
function renderLastData(data) {
|
||||
const last = data[data.length - 1];
|
||||
$("last-date").textContent = last.dia;
|
||||
$("last-temp").textContent = last.temp_max + "°C / " + last.temp_min + "°C";
|
||||
$("last-humidity").textContent = last.humedad + " %";
|
||||
$("last-rain").textContent = last.lluvia + " mm";
|
||||
$("last-wind").textContent = last.viento_velocidad + " km/h";
|
||||
$("last-sunrise").textContent = last.amanecer;
|
||||
$("last-sunset").textContent = last.anochecer;
|
||||
}
|
||||
|
||||
/* ---------- RESUMEN DEL MES ---------- */
|
||||
|
||||
// ====================
|
||||
// Estadísticas del mes seleccionado
|
||||
// ====================
|
||||
function renderMonthStats(data) {
|
||||
const now = new Date();
|
||||
const month = now.getMonth();
|
||||
const year = now.getFullYear();
|
||||
|
||||
const monthData = data.filter(d => {
|
||||
const date = new Date(d.dia);
|
||||
return date.getMonth() === month && date.getFullYear() === year;
|
||||
});
|
||||
const monthData = data.filter(d => new Date(d.dia).getMonth() === selectedMonth);
|
||||
|
||||
if (!monthData.length) return;
|
||||
|
||||
const maxTemps = monthData.map(d => d.temp_max);
|
||||
const minTemps = monthData.map(d => d.temp_min);
|
||||
|
||||
const lluvia = monthData.reduce((sum, d) => sum + parseFloat(d.lluvia), 0);
|
||||
const humedad = (
|
||||
monthData.reduce((sum, d) => sum + parseFloat(d.humedad), 0) /
|
||||
monthData.length
|
||||
).toFixed(1);
|
||||
const humedad = (monthData.reduce((sum, d) => sum + parseFloat(d.humedad), 0) / monthData.length).toFixed(1);
|
||||
|
||||
$("month-days").textContent = monthData.length;
|
||||
$("month-max").textContent = Math.max(...maxTemps) + "°C";
|
||||
|
|
@ -79,24 +70,17 @@ function renderMonthStats(data) {
|
|||
$("month-humidity").textContent = humedad + " %";
|
||||
}
|
||||
|
||||
/* ---------- TENDENCIA HISTÓRICA ---------- */
|
||||
|
||||
// ====================
|
||||
// Tendencia histórica
|
||||
// ====================
|
||||
function renderTrend(data) {
|
||||
const now = new Date();
|
||||
const month = now.getMonth();
|
||||
|
||||
const byYear = {};
|
||||
|
||||
data.forEach(d => {
|
||||
const date = new Date(d.dia);
|
||||
|
||||
if (date.getMonth() === month) {
|
||||
if (date.getMonth() === selectedMonth) {
|
||||
const year = date.getFullYear();
|
||||
|
||||
if (!byYear[year]) {
|
||||
byYear[year] = { max: [], min: [], rain: [] };
|
||||
}
|
||||
|
||||
if (!byYear[year]) byYear[year] = { max: [], min: [], rain: [] };
|
||||
byYear[year].max.push(d.temp_max);
|
||||
byYear[year].min.push(d.temp_min);
|
||||
byYear[year].rain.push(parseFloat(d.lluvia));
|
||||
|
|
@ -104,31 +88,43 @@ function renderTrend(data) {
|
|||
});
|
||||
|
||||
const container = $("trend-container");
|
||||
container.innerHTML = "<table><tr><th>Año</th><th>Temp. Máx. Avg</th><th>Temp. Mín. Avg</th><th>Lluvia Total</th></tr>";
|
||||
container.innerHTML = "<table><thead><tr><th>Año</th><th>Máx</th><th>Mín</th><th>Lluvia</th></tr></thead><tbody>";
|
||||
|
||||
Object.keys(byYear)
|
||||
.sort()
|
||||
.forEach(year => {
|
||||
const maxAvg = (byYear[year].max.reduce((a, b) => a + b, 0) / byYear[year].max.length).toFixed(1);
|
||||
const minAvg = (byYear[year].min.reduce((a, b) => a + b, 0) / byYear[year].min.length).toFixed(1);
|
||||
const rainTotal = (byYear[year].rain.reduce((a, b) => a + b, 0)).toFixed(1);
|
||||
Object.keys(byYear).sort().forEach(year => {
|
||||
const maxAvg = (byYear[year].max.reduce((a,b)=>a+b,0)/byYear[year].max.length).toFixed(1);
|
||||
const minAvg = (byYear[year].min.reduce((a,b)=>a+b,0)/byYear[year].min.length).toFixed(1);
|
||||
const rainTotal = byYear[year].rain.reduce((a,b)=>a+b,0).toFixed(1);
|
||||
|
||||
container.innerHTML += `
|
||||
<tr>
|
||||
<td><strong>${year}</strong> </td>
|
||||
<td>${maxAvg}°C</td>
|
||||
<td>${minAvg}°C</td>
|
||||
<td>${rainTotal} mm</td>
|
||||
<td><strong>${year}</strong></td>
|
||||
<td>Máx ${maxAvg}°C</td>
|
||||
<td>Mín ${minAvg}°C</td>
|
||||
<td>Lluvia ${rainTotal} mm</td>
|
||||
</tr>
|
||||
`;
|
||||
});
|
||||
container.innerHTML += "</table>";
|
||||
container.innerHTML += "</tbody></table>";
|
||||
}
|
||||
|
||||
/* ---------- INIT ---------- */
|
||||
|
||||
// ====================
|
||||
// Botones de mes
|
||||
// ====================
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
$("year").textContent = new Date().getFullYear();
|
||||
updateMonthHeader();
|
||||
loadStats();
|
||||
});
|
||||
|
||||
$("prev-month").addEventListener("click", () => {
|
||||
selectedMonth = (selectedMonth + 11) % 12;
|
||||
updateMonthHeader();
|
||||
loadStats();
|
||||
});
|
||||
|
||||
$("next-month").addEventListener("click", () => {
|
||||
selectedMonth = (selectedMonth + 1) % 12;
|
||||
updateMonthHeader();
|
||||
loadStats();
|
||||
});
|
||||
|
||||
$("year").textContent = new Date().getFullYear();
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in New Issue