-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
66 lines (59 loc) · 2.56 KB
/
Copy pathscripts.js
File metadata and controls
66 lines (59 loc) · 2.56 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
65
66
function getWeather(){
const apikey = "API KEY";
const city = document.getElementById("city").value;
const url = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&units=imperial&appid=${apikey}`
fetch(url)
.then(response => response.json())
.then(data => {
displayWeather(data);
console.log(data)
})
.catch(error => {
console.log(error)
console.error('Error fetching weather data:', error);
alert(`Error fetching weather data for "${city}". Please try again.`);
});
}
function displayWeather(data){
const{name} = data
const{icon, description} = data.weather[0];
const{temp, feels_like, temp_min, temp_max, humidity} = data.main
const{speed} = data.wind;
document.querySelector('.container').classList.remove('loading')
document.getElementById('location').innerText = `Weather in ${name}`;
document.getElementById('temperature').innerText = `${temp}°F`;
document.getElementById('feels').innerText = `Feels like: ${feels_like}°F`;
document.getElementById('icon').src = `https://openweathermap.org/img/wn/${icon}.png`;
document.getElementById('description').innerText = description;
document.getElementById('high').innerText = `High: ${temp_max}°F`;
document.getElementById('low').innerText = `Low: ${temp_min}°F`;
document.getElementById('humidity').innerText = `Humidity: ${humidity}%`;
document.getElementById('wind').innerText = `Wind: ${speed}mph`;
setBackgroundImage(name);
let milliseconds = 300;
setTimeout(() =>{
let weatherInfo = document.querySelector('.weatherInfo');
weatherInfo.style.display = "auto";
weatherInfo.style.transition = "opacity 2s";
weatherInfo.style.opacity = 1;
}, milliseconds)
}
function setBackgroundImage(name) {
const apiKey = 'API KEY'
const engineID = 'ENGINE ID'
const url = `https://www.googleapis.com/customsearch/v1?key=${apiKey}&cx=${engineID}&q=${encodeURIComponent(`${name} city`)}&searchType=image&num=1`;
fetch(url)
.then(response =>response.json())
.then(data => {
if (data.items && data.items.length > 0) {
const imageURL = data.items[0].link;
document.body.style.backgroundImage = `url(${imageURL})`;
document.body.style.backgroundSize = 'cover';
} else {
console.error(`No image found for the city ${name}.`)
}
})
.catch(error => {
console.error('Error fetching image data:', error);
});
}