feat: Add location selection to weather overlay

This commit is contained in:
2025-10-31 10:15:20 +01:00
parent e03d50ed5b
commit ce93b8a092
2 changed files with 63 additions and 13 deletions

View File

@@ -32,22 +32,54 @@
</div>
</div>
<div id="location-container">
<input type="text" id="city-input" placeholder="Enter city name">
<button id="update-button">Update</button>
</div>
<script>
const latitude = 40.71;
const longitude = -74.01;
const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true`;
const defaultLatitude = 40.71;
const defaultLongitude = -74.01;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const temperature = data.current_weather.temperature;
const weatherCode = data.current_weather.weathercode;
function fetchWeather(latitude, longitude) {
const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true`;
document.getElementById('temperature').textContent = `${temperature}°C`;
document.getElementById('weather-description').textContent = getWeatherDescription(weatherCode);
document.getElementById('weather-icon').src = getWeatherIcon(weatherCode);
})
.catch(error => console.error('Error fetching weather data:', error));
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const temperature = data.current_weather.temperature;
const weatherCode = data.current_weather.weathercode;
document.getElementById('temperature').textContent = `${temperature}°C`;
document.getElementById('weather-description').textContent = getWeatherDescription(weatherCode);
document.getElementById('weather-icon').src = getWeatherIcon(weatherCode);
})
.catch(error => console.error('Error fetching weather data:', error));
}
function getCoordinates(city) {
const geocodingUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${city}`;
fetch(geocodingUrl)
.then(response => response.json())
.then(data => {
if (data.results && data.results.length > 0) {
const latitude = data.results[0].latitude;
const longitude = data.results[0].longitude;
fetchWeather(latitude, longitude);
} else {
alert("Could not find city. Please try again.");
}
})
.catch(error => console.error('Error fetching coordinates:', error));
}
document.getElementById('update-button').addEventListener('click', () => {
const city = document.getElementById('city-input').value;
if (city) {
getCoordinates(city);
}
});
function getWeatherDescription(code) {
// This is a simplified mapping. You can expand it for more detailed descriptions.
@@ -74,6 +106,9 @@
if (code > 94) return "https://openweathermap.org/img/wn/11d@2x.png"; // Thunderstorm
return "https://openweathermap.org/img/wn/03d@2x.png"; // Cloudy
}
// Initial fetch with default location
fetchWeather(defaultLatitude, defaultLongitude);
</script>
</body>
</html>