Untitled
4 months ago in HTML
<!DOCTYPE html>
<html>
<head>
<title>Weather Ease</title>
<style>
*{
font-size:153%;
}
</style>
</head>
<body>
<h2>Live Weather Report</h2>
<p>Click the button to get your coordinates and fetch live weather data.</p>
<button onclick="getLocation()">Get Weather</button>
<p id="demo"></p>
<p id="weather"></p>
<p><a href="https://manasmm007.github.io/Manasmm007">Main Menu</a></p>
<script>
const x = document.getElementById("demo");
const weatherDisplay = document.getElementById("weather");
function getLocation() {
try {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getWeatherData, handleLocationError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
} catch (error) {
x.innerHTML = error.message;
}
}
function getWeatherData(position) {
const { latitude, longitude } = position.coords;
x.innerHTML = "Latitude: " + latitude + "<br>Longitude: " + longitude;
const apiKey = '42465ecf00fd1d0a9199ca3ea77a9564';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`;
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok - ' + response.status + ' ' + response.statusText);
}
return response.json();
})
.then(weatherData => {
console.log('Weather Data:', weatherData);
const temperature = weatherData.main.temp;
const description = weatherData.weather[0].description;
const cityName = weatherData.name;
const country = weatherData.sys.country;
const weatherInfo = `Weather in ${cityName}, ${country}: ${temperature}°C, ${description}`;
weatherDisplay.innerHTML = weatherInfo;
})
.catch(error => {
weatherDisplay.innerHTML = `Error fetching weather data: ${error.message}`;
console.error('Error fetching weather data:', error);
});
}
function handleLocationError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred.";
break;
}
}
</script>
</body>
</html>