-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
64 lines (53 loc) · 2.19 KB
/
Copy pathmain.js
File metadata and controls
64 lines (53 loc) · 2.19 KB
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
import './global.css';
import axios from 'axios';
const content = document.getElementById('content');
const searchBar = document.getElementById('searchBar');
let weatherData = [];
const loadForecast = async (city) => {
try {
// Step 1: Get latitude and longitude using Geocoding API
const geoResponse = await axios.get(
`https://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=e479981d2e9be2d6aac75e850883c299`
);
if (geoResponse.data.length === 0) {
throw new Error('City not found');
}
const { lat, lon } = geoResponse.data[0];
// Step 2: Get the weather data using the One Call API 3.0
const endpoint = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=e479981d2e9be2d6aac75e850883c299`
);
weatherData = endpoint;
// eslint-disable-next-line
displayForecast(weatherData);
} catch (err) {
// eslint-disable-next-line
console.error(err);
}
};
loadForecast('Lisabon');
searchBar.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
loadForecast(searchBar.value);
}
});
const displayForecast = (forecast) => {
const htmlString = `
<div>
<p class="text-2xl font-light">Weather in ${forecast.data.name}</p>
<h1 class="text-8xl py-2 m-2 font-bold">${Math.round(forecast.data.main.temp)}℃</h1>
<div class="flex items-center space-x-3 py-1 text-lg font-bold">
<img src="https://openweathermap.org/img/wn/${forecast.data.weather[0].icon}.png"/>
<p>${forecast.data.weather[0].description}</p>
</div>
<ul class="space-y-3 mt-3 font-extrabold text-lg">
<li>Wind Speed:<span class="text-lg ml-2">${forecast.data.wind.speed}</span></li>
<li>Visibility:<span class="ml-2">${Math.round(forecast.data.visibility)}km</span></li>
<li>Feels Like:<span class=" ml-2">${Math.round(forecast.data.main.feels_like)}℃</span></li>
<li>Pressure:<span class=" ml-2">${forecast.data.main.pressure}</span></li>
<li>Humidity:<span class=" ml-2">${forecast.data.main.humidity}%</span></li>
</ul>
<p class="mt-6 text-xs text-yellow-300">Powered by Open Weather API</p>
</div>`;
content.innerHTML = htmlString;
};