class WeatherWidget extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
--°
`;
this.fetchWeather();
}
async fetchWeather() {
try {
// Get user's location
const position = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
// Fetch weather data
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&appid=YOUR_API_KEY`
);
if (!response.ok) throw new Error('Weather data not available');
const data = await response.json();
this.updateWeather(data);
} catch (error) {
console.error('Error fetching weather:', error);
this.shadowRoot.querySelector('.location').textContent = 'Weather unavailable';
}
}
updateWeather(data) {
const shadow = this.shadowRoot;
shadow.querySelector('.location').textContent = data.name;
shadow.querySelector('.temperature').textContent = `${Math.round(data.main.temp)}°C`;
shadow.querySelector('.humidity').textContent = `${data.main.humidity}%`;
shadow.querySelector('.wind').textContent = `${Math.round(data.wind.speed * 3.6)} km/h`;
shadow.querySelector('.clouds').textContent = `${data.clouds.all}%`;
shadow.querySelector('.pressure').textContent = `${data.main.pressure} hPa`;
const iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
shadow.querySelector('.weather-icon').src = iconUrl;
shadow.querySelector('.weather-icon').alt = data.weather[0].description;
}
}
customElements.define('weather-widget', WeatherWidget);