Untitled
unknown
plain_text
2 years ago
7.7 kB
2
Indexable
const apiKey = '065b816a82110d32a0a268b7666da270'; const assignedCity = 'Milton Keynes'; const searchInput = document.querySelector('input'); const searchButton = document.querySelector('button'); const weatherDiv = document.querySelector('.weather'); const historyButton = document.querySelector('.historyButton'); var weatherHistoryDiv = document.getElementById("weatherHistory"); var cityToSearch=assignedCity; weatherHistoryDiv.style.display = "none"; const getWeatherData = async (city) => { try { const response = await fetch( // `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}` `https://history.openweathermap.org/data/2.5/history/city?id=2885679&type=day&appid=065b816a82110d32a0a268b7666da270&cnt=7` ); const data = await response.json(); console.log("data is found") return data; } catch (error) { console.log(error); } }; function insertWeather(id,city,day, temperature, min, max, humidity, description) { var dataObj = { id:id, city:city, day: day, temperature: temperature, min: min, max: max, temperature: temperature, humidity: humidity, description: description }; $.ajax({ type: "POST", url: "BrabimBaskota_2331410_insert.php", data: dataObj, success: function(response) { console.log(response); }, error: function(xhr, status, error) { console.log("Error: " + xhr.responseText); } }); } /*------------------------------------------------*/ function displayWeather() { $.ajax({ url: "BrabimBaskota_2331410_fetch.php", // replace with the URL of your API type: "GET", dataType: "json", success: function(data) { var table = "<table class='styled-table'><tr><th>Day</th><th>Temperature</th><th>Min</th><th>Max</th><th>Humidity</th><th>Description</th></tr>"; $.each(data, function(index, element) { table += "</td><td>" + element.day + "</td><td>" + element.temp + "</td><td>" + element.min + "</td><td>" + element.max + "</td><td>" + element.humidity + "</td><td>" + element.description + "</td></tr>"; }); table += "</table>"; $("#weatherHistory").html(table); // replace with the ID of the HTML element where you want to display the table }, error: function(jqXHR, textStatus, errorThrown) { console.log("Error fetching weather data: " + textStatus + ", " + errorThrown); } }); } /*--------------------------------------------------*/ const showWeatherData = (data) => { // Loop through the items in the "list" array using a forEach loop data.list.forEach((listItem, index) => { const city = cityToSearch; const date = new Date().toDateString(); const condition = listItem.weather[0].description; const icon = `http://openweathermap.org/img/w/${listItem.weather[0].icon}.png`; const temperature = listItem.main.temp; const humidity = listItem.main.humidity; const windspeed = listItem.wind.speed; const rainfall = listItem.rain ? listItem.rain['1h'] : '0'; var dateFromUnix = new Date(listItem.dt * 1000); var dayFromDate= dateFromUnix.getDay()+1; console.log(dayFromDate); const storedData = { city, date, condition, icon, temperature, humidity, windspeed, rainfall }; const existingDataString = localStorage.getItem('weatherData'); let existingData=[]; if (existingDataString) { existingData = JSON.parse(existingDataString); } if (!isDataAlreadyStored(city)) { // Add the new data to the existing data existingData.push(storedData); // Convert the updated data to a JSON string const updatedDataString = JSON.stringify(existingData); // Store the updated JSON string in local storage localStorage.setItem('weatherData', updatedDataString); } const daysMap = { 1: "Sunday", 2: "Monday", 3: "Tuesday", 4: "Wednesday", 5: "Thursday", 6: "Friday", 7: "Saturday" }; //inserting to API insertWeather(dayFromDate,city,daysMap[dayFromDate],temperature,listItem.main.temp_min,listItem.main.temp_max,listItem.main.humidity,condition); weatherDiv.innerHTML = `<h2>${city} (${date})</h2> <div> <img src="${icon}" alt="${condition}"> <p>${condition}</p> </div> <div> <p>Temperature: ${temperature} °C</p> </div> <div><p> Humidity: ${humidity}%</p> </div><div> <p>Windspeed: ${windspeed}m/s</p> <p>Rainfall: ${rainfall}mm</p> </div>`; }); /*-----------------------------------------------------------*/ //search bitton click historyButton.addEventListener('click', async () => { if (weatherHistoryDiv.style.display === "none") { weatherHistoryDiv.style.display = "block"; displayWeather() } else { weatherHistoryDiv.style.display = "none"; } }); // Show weather data for the assigned city on page load /*---------------------------------------------------------*/ //search button onclick handler searchButton.addEventListener('click', async () => { const city = searchInput.value; //check in local storage before calling to api if (isDataAlreadyStored(city)) { console.log("data found in local") fetchFromLocalStorage(city) } else { //call api console.log("data not found in local, calling api") const data = await getWeatherData(city); showWeatherData(data); cityToSearch=city; searchInput.value = ''; } }); } /*------------------------------------------------------*/ //run on init if (isDataAlreadyStored(assignedCity)) { console.log("data already stored") fetchFromLocalStorage(assignedCity); } else { console.log("data not found in local") getWeatherData(assignedCity).then((data) => showWeatherData(data)); } /*-----------------------------------------------------*/ /*function to check city in local storage*/ function isDataAlreadyStored(city) { const existingDataString = localStorage.getItem('weatherData'); if (existingDataString) { const existingData = JSON.parse(existingDataString); return existingData.some(item => item.city.toLowerCase() === city.toLowerCase()); } return false; } /*-----------------------------------------------------------*/ /*fetch from local storage*/ function fetchFromLocalStorage(city){ // Retrieve the JSON string from local storage const storedDataString = localStorage.getItem('weatherData'); // Convert the JSON string back to an array of objects const storedData = JSON.parse(storedDataString); // Specify the city for which you want to access the values const targetCity =city; // Find the data object for the target city const targetData = storedData.find(item => item.city.toLowerCase() === targetCity.toLowerCase()); if (targetData) { // Access the individual values for the target city const city = targetData.city; const date = targetData.date; const condition = targetData.condition; const icon = targetData.icon; const temperature = targetData.temperature; const humidity = targetData.humidity; const windspeed = targetData.windspeed; const rainfall = targetData.rainfall; // Use the values as needed console.log(city, date, condition, icon, temperature, humidity, windspeed, rainfall); weatherDiv.innerHTML = `<h2>${city} (${date})</h2> <div> <img src="${icon}" alt="${condition}"> <p>${condition}</p> </div> <div> <p>Temperature: ${temperature} °C</p> </div> <div><p> Humidity: ${humidity}%</p> </div><div> <p>Windspeed: ${windspeed}m/s</p> <p>Rainfall: ${rainfall}mm</p> </div>`; } else { // Handle the case when data for the target city is not found console.log(`Data not found for ${targetCity}`); } }
Editor is loading...