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");
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}`
);
const data = await response.json();
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) => {
const city = data.name;
const date = new Date().toDateString();
const condition = data.weather[0].description;
const icon = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`;
const temperature = data.main.temp;
const humidity = data.main.humidity;
const windspeed = data.wind.speed;
const rainfall = data.rain ? data.rain['1h'] : '0';
var dateFromUnix = new Date(data.dt * 1000);
var dayFromDate= dateFromUnix.getDay()+1
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],data.main.temp,data.main.temp_min,data.main.temp_max,data.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>`;
}
/*-----------------------------------------------------*/
/*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}`);
}
}
/*-----------------------------------------------------------*/
//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);
searchInput.value = '';
}
});
if (isDataAlreadyStored(assignedCity)) {
console.log("data already stored")
fetchFromLocalStorage(assignedCity)
}
else {
console.log("data not found in local")
getWeatherData(assignedCity).then((data) => showWeatherData(data));
}
/*------------------------------------------------------*/
//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));
}