-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
134 lines (107 loc) · 4.76 KB
/
script.js
File metadata and controls
134 lines (107 loc) · 4.76 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
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
import api from "./config.js";
const container = document.querySelector(".container"),
inputBox = container.querySelector(".input-box"),
weatherBox = container.querySelector(".weather-box"),
infoText = inputBox.querySelector(".info-text"),
inputField = inputBox.querySelector("input"),
inputBtn = inputBox.querySelector("button"),
arrowBack = container.querySelector("header i");
// Enviar os dados ao apertar enter
inputField.addEventListener("keyup", e => {
if(e.key == "Enter" && inputField.value != ""){
requestAPI(inputField.value);
}
});
//Enviar os dados ao apertar o botão
inputBtn.addEventListener("click", () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccess, onError)
}else {
console.log("O navegador não suporta Geolocation.");
}
})
// Caso o geolocation funcione
function onSuccess(position){
let apiReq = `https://api.openweathermap.org/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&appid=${api.key}&units=${api.units}&lang=${api.lang}`;
fetchData(apiReq);
}
// Caso o geolocation não funcione
function onError(error) {
if(error.code == 1) {
infoText.innerText = "O usuário negou o acesso.";
}else if(error.code == 2){
infoText.innerText = "Posição atual indisponível.";
}else {
infoText.innerText = "Tempo esgotado.";
}
infoText.classList.add('error');
}
// Armazenando a requisição da API em uma variável
function requestAPI(city) {
let apiReq = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api.key}&units=${api.units}&lang=${api.lang}`;
fetchData(apiReq);
}
// Fazendo a requisição na API
function fetchData(apiReq){
//Insere um novo texto em infoText e adiciona uma nova classe
infoText.textContent = "Procurando...";
infoText.classList.add('pending');
// Pega a resposta e retorna transformando em um objeto JS
// para então chamar a função weatherDetails, passando o resultado como argumento
fetch(apiReq)
.then(response => response.json())
.then(data => weatherDetails(data));
}
// exibindo todos os detalhes na tela
function weatherDetails(info) {
if(info.cod == 404) {
infoText.innerText = `'${inputField.value}': Cidade não encontrada.`;
infoText.classList.replace('pending', 'error');
}else {
// reseta os valores do campo de entrada (inputField) e da caixa de texto (infoText). Adiciona uma classe ao ".container"
inputField.value = '';
infoText.classList.remove('pending', 'error');
container.classList.add('active');
//exibe todos os dados na tela
// location
weatherBox.querySelector('.location span').innerText = `${info.name}, ${info.sys.country}`;
//date
let date = new Date();
let months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
let day = date.getDate();
let month = months[date.getMonth()]; // mes[numero do mes]
let year = date.getFullYear();
weatherBox.querySelector('.date span').innerText = `${day} de ${month} de ${year}`;
// temp
weatherBox.querySelector('.temp .num').innerText = Math.floor(info.main.temp);
//weather
let weatherId = info.weather[0].id;
let weatherInfo = info.weather[0].description;
let weatherIcon;
//weather icon conditions
if(weatherId >= 200 || weatherId <= 232){
weatherIcon = '/Weather Icons/storm.svg';
}else if(weatherId >= 300 || weatherId <= 321){
weatherIcon = '/Weather Icons/rain.svg';
}else if(weatherId >= 500 || weatherId <= 531){
weatherIcon = '/Weather Icons/rain.svg';
}else if(weatherId >= 600 || weatherId <= 622){
weatherIcon = '/Weather Icons/snow.svg';
}else if(weatherId >= 701 || weatherId <= 781){
weatherIcon = '/Weather Icons/haze.svg';
}else if(weatherId == 800){
weatherIcon = '/Weather Icons/clear.svg';
}else if(weatherId >= 801 || weatherId <= 804){
weatherIcon = '/Weather Icons/cloud.svg';
}
weatherBox.querySelector('.weather img').src = weatherIcon;
weatherBox.querySelector('.weather span').innerText = weatherInfo;
// bottom details
weatherBox.querySelector('.bottom-details .feels-like .num').innerText = Math.floor(info.main.feels_like);
weatherBox.querySelector('.bottom-details .humidity .num').innerText = `${info.main.humidity}%`;
}
}
// bottão arrowBack
arrowBack.addEventListener("click", ()=> {
container.classList.remove('active');
});