frontend-1

ref: master

js/weather.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
 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
const weatherApiKey = "20e17f827394ac7eeb484d06ff9e2527";
const tabs = document.querySelectorAll(".tab-button");
const tabContents = document.querySelectorAll(".tab-content");

// Tabs stuff
const initializeTabs = () => {
  tabs.forEach((tab) => {
    tab.addEventListener("click", () => switchTab(tab));
  });
}

const switchTab = (tab) => {
  tabs.forEach((t) => t.classList.remove("active"));
  tabContents.forEach((content) => content.classList.remove("active"));

  tab.classList.add("active");
  document.getElementById(tab.dataset.tab).classList.add("active");
}

const initializeApp = () => {
  initializeTabs();
  getUserLocationWeather();
}

// Geo stuff

const getUserLocationWeather = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => fetchWeatherByCoordinates(position.coords),
      handleLocationError
    );
  } else {
    updateWeatherDisplay("location", "Geolocalização não suportada pelo navegador.");
  }
}

function fetchWeatherByCoordinates(coords) {
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&units=metric&lang=pt_br&appid=${weatherApiKey}`;

  fetch(apiUrl)
    .then((response) => response.json())
    .then((data) => displayCurrentWeather(data))
    .catch(() => updateWeatherDisplay("location", "Erro ao obter o clima."));
}

const displayCurrentWeather = (data) => {
  updateWeatherDisplay("location", `Cidade: ${data.name}`);
  updateWeatherDisplay("temperature", `Temperatura: ${data.main.temp.toFixed(1)}°C`);
  updateWeatherDisplay("conditions", `Condições: ${data.weather[0].description}`);
}

const handleLocationError = (error) => {
  const errorMessage = {
    1: "Permissão negada para acessar localização.",
    2: "Localização indisponível.",
    3: "Tempo de solicitação esgotado.",
  };

  updateWeatherDisplay("location", errorMessage[error.code] || "Erro desconhecido.");
}

const updateWeatherDisplay = (elementId, textContent) => {
  const element = document.getElementById(elementId);
  if (element) {
    element.textContent = textContent;
  }
}

// By city

const initializeCitySearch = () => {
  const cityForm = document.getElementById("city-form");
  cityForm.addEventListener("submit", handleCitySearch);
}

const handleCitySearch = (event) => {
  event.preventDefault();

  const cityInput = document.getElementById("city-input").value.trim();

  if (cityInput) {
    fetchWeatherByCity(cityInput);
  }
}

const fetchWeatherByCity = (city) => {
  const cityWeatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&lang=pt_br&appid=${weatherApiKey}`;

  fetch(cityWeatherUrl)
    .then((response) => response.json())
    .then((data) => displayCityWeather(data))
    .catch(() => updateWeatherDisplay("city-location", "Erro ao buscar o clima para essa cidade."));
}

const displayCityWeather = (data) => {
  updateWeatherDisplay("city-location", `Localização: ${data.name}`);
  updateWeatherDisplay("city-temperature", `Temperatura: ${data.main.temp.toFixed(1)}°C`);
  updateWeatherDisplay("city-conditions", `Condições: ${data.weather[0].description}`);
}

// Rig everything and boot this fucking shit
document.addEventListener("DOMContentLoaded", () => {
  initializeApp();
  initializeCitySearch();
});