Advertisement
magrega

hw2 task5

Feb 1st, 2023
892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 5. Вам необходимо создать приложение по поиску погоды:
  2. //  • используйте бесплатное REST API (https://weatherstack.com/) для данных;
  3. //  • создайте index.html с разметкой:
  4. //  ◦ html input & label, //  ◦ html button
  5. //  ◦ div элементы для полученных данных
  6. //  ◦ для построение красивого UI/UX используйте воображение
  7. //  • создайте style.css файл со стилями (попробуйте сделать это красиво, применив свои навыки), include it into index.html
  8. //  • создайте index.js файл со следующей логикой:
  9. //  ◦ когда пользователь кликает кнопку Поиск или нажимает Enter на клавиатуре после ввода строки поиска, он должен получить таблицу с данными о погоде в выбранном городе;
  10. //  ◦ подумайте о грамотной валидации полей;
  11.  
  12. //variables
  13. const HOST = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/";
  14. const KEY = "CU6C3P9UUA3R89ZXRPGWJHH7C";
  15. const weatherContainer = document.querySelector('.weatherData');
  16. const inputElement = document.querySelector(".input");
  17. const tbody = document.querySelector('tbody');
  18. const table = document.querySelector('table');
  19.  
  20. //functions
  21. async function getWeatherData(obj) {
  22.     const weather = {};
  23.     weather.description = obj.description;
  24.     weather["Clouds"] = obj.currentConditions.conditions;
  25.     weather["Feels like"] = `${Math.floor(((+(obj.currentConditions.feelslike) - 32) * 5 / 9))}C`;
  26.     weather["Pressure"] = `${obj.currentConditions.pressure}MB`;
  27.     weather["Temperature"] = `${Math.floor(((+(obj.currentConditions.temp) - 32) * 5 / 9))}C`;
  28.     weather["Tomorrow"] = `${Math.floor(((+(obj.days[1].temp) - 32) * 5 / 9))}C`;
  29.     await getCityAndCountry(obj.latitude, obj.longitude, weather);
  30.     return weather;
  31. };
  32.  
  33. function setLocalStorage(obj) {
  34.     localStorage.setItem("city", obj.city);
  35.     localStorage.setItem("country", obj.country);
  36.     localStorage.setItem("temp", obj["Temperature"]);
  37.     localStorage.setItem("feelslike", obj["Feels like"]);
  38. }
  39.  
  40. function setWeatherInfo(obj) {
  41.     weatherContainer.innerHTML = "";
  42.     weatherContainer.classList.add('seeable');
  43.     document.querySelector('form').reset();
  44.     return obj.then(obj => {
  45.         for (const key in obj) {
  46.             if (key === 'city' || key === 'country') continue;
  47.             const P = document.createElement('p');
  48.             P.innerHTML =`${key}: ${obj[key]}`;
  49.             weatherContainer.append(P);
  50.         };
  51.         return obj;
  52.     });
  53.  
  54. };
  55.  
  56. function getLocation() {
  57.     return new Promise((res, rej) => {
  58.         navigator.geolocation ? navigator.geolocation.getCurrentPosition(res, rej) : alert("Geolocation not supported");
  59.     })
  60. };
  61.  
  62. function fetchRequest(request) {
  63.  
  64.     return fetch(request).then(item => item.json()).catch((err) => alert(err));
  65. }
  66.  
  67. function getCityAndCountry(lat, lon, obj) {
  68.     return fetch(`https://geocode.maps.co/reverse?lat=${lat}&lon=${lon}`).then(item => item.json()).then(item => {
  69.         obj.city = item.address.city ?? item.address.state ?? item.address.town;
  70.         obj.country = item.address.country;
  71.         weatherContainer.prepend(`${obj.country}, ${obj.city}`)
  72.         return item.address;
  73.     });
  74. }
  75.  
  76.  
  77. const cityArr = []; // don;t like using array
  78. function makeTable() {
  79.     const storageCity = localStorage.getItem('city');
  80.    
  81.     function makeRowsandCells(index = 0, update = '') {
  82.         const row = tbody.insertRow(index);
  83.         const cityCell = row.insertCell();
  84.         cityCell.innerHTML = localStorage.getItem('city') + update;
  85.         const cityCell1 = row.insertCell();
  86.         cityCell1.innerHTML = localStorage.getItem('country');
  87.         const cityCell2 = row.insertCell();
  88.         cityCell2.innerHTML = localStorage.getItem('temp');
  89.         const cityCell3 = row.insertCell();
  90.         cityCell3.innerHTML = localStorage.getItem('feelslike');
  91.     }
  92.  
  93.  
  94.     if (cityArr.includes(storageCity)) {
  95.         tbody.deleteRow(cityArr.indexOf(storageCity));
  96.         makeRowsandCells(cityArr.indexOf(storageCity), " UPDATE");
  97.  
  98.     } else {
  99.         makeRowsandCells();
  100.         cityArr.unshift(storageCity);
  101.     }
  102.  
  103.     if (tbody.children[0]) {
  104.         table.classList.add('table-visible');
  105.     }
  106.  
  107. }
  108.  
  109. function clearTableAndLocalStorage() {
  110.     table.classList.remove('table-visible');
  111.     tbody.innerHTML = '';
  112.     cityArr.length = 0;
  113.     localStorage.clear();
  114.  
  115. }
  116.  
  117. //eventlisteners
  118. document.querySelector('.search').addEventListener('click', async function (e) {
  119.     e.preventDefault();
  120.  
  121.     if (inputElement.value === '') {
  122.         alert("Input can't be empty");
  123.         return;
  124.     };
  125.  
  126.     const query = inputElement.value;
  127.     const request = `${HOST}${query}?unitGroup=us&key=${KEY}&contentType=json`;
  128.     fetchRequest(request).then(item => setWeatherInfo(getWeatherData(item))).then(item => setLocalStorage(item)).then(() => makeTable());
  129.  
  130. });
  131.  
  132. document.querySelector('.myWeather').addEventListener('click', async function () {
  133.     const query = await getLocation();
  134.     const request = `${HOST}${query.coords.latitude},${query.coords.longitude}?unitGroup=us&key=${KEY}&contentType=json`;
  135.     fetchRequest(request).then(item => setWeatherInfo(getWeatherData(item))).then(item => setLocalStorage(item)).then(() => makeTable());
  136. });
  137.  
  138. document.querySelector('.clear').addEventListener('click', function () {
  139.     clearTableAndLocalStorage();
  140. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement