-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
64 lines (60 loc) · 2.76 KB
/
script.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
document.addEventListener("DOMContentLoaded", function () {
const cityInput = document.getElementById("cityInput");
const searchButton = document.getElementById("searchButton");
const locationButton = document.getElementById("locationButton");
const weatherInfo = document.getElementById("weatherInfo");
const apiKey = "b71debe44a3ef7727c30a3fbc9455883"; // Reemplaza con tu API Key
// Buscar clima por ciudad
searchButton.addEventListener("click", function () {
const city = cityInput.value;
if (city === "") {
alert("¡Escribe el nombre de una ciudad!");
return;
}
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=es`)
.then((response) => response.json())
.then((data) => {
if (data.cod === "404") {
weatherInfo.innerHTML = "<p>Ciudad no encontrada 😢</p>";
return;
}
showWeather(data);
})
.catch((error) => {
console.error("Error al buscar el clima:", error);
weatherInfo.innerHTML = "<p>Hubo un error al buscar el clima. Intenta de nuevo.</p>";
});
});
// Obtener clima por ubicación
locationButton.addEventListener("click", function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=es`)
.then((response) => response.json())
.then((data) => {
showWeather(data);
})
.catch((error) => {
console.error("Error al obtener la ubicación:", error);
weatherInfo.innerHTML = "<p>Hubo un error al obtener tu ubicación. Intenta de nuevo.</p>";
});
});
} else {
alert("Tu navegador no soporta la geolocalización.");
}
});
// Mostrar el clima
function showWeather(data) {
const { name, main, weather, wind } = data;
weatherInfo.innerHTML = `
<h2>${name}</h2>
<p>Temperatura: ${main.temp}°C</p>
<p>Humedad: ${main.humidity}%</p>
<p>Viento: ${wind.speed} m/s</p>
<p>Clima: ${weather[0].description}</p>
<img src="http://openweathermap.org/img/wn/${weather[0].icon}@2x.png" alt="${weather[0].description}">
`;
}
});