addlog('start dashboard.js'); // obter coordenadas gps var clat; var clon; var cidade; var concelho; var distrito; var idDistrito; var idAreaAviso; var areaAviso; var avisoDB = []; var ipmaGlobalIdLocal; const API_KEY = '64f60853740a1ee3ba20d0fb595c97d5' var units = "metric"; var heroWeatherNowTemp = document.getElementById("heroWeatherNowTemp"); var heroWeatherNowLocation = document.getElementById("heroWeatherNowLocation"); var heroWeatherNowDescription = document.getElementById("heroWeatherNowDescription"); var heroWeatherThermalSensation = document.getElementById("heroWeatherThermalSensation"); var heroWeatherTempMinMax = document.getElementById("heroWeatherTempMinMax"); var heroAlerts = document.getElementById("heroAlerts"); var heroAlertsList = document.getElementById("heroAlertsList"); var heroAlertsIcon = document.getElementById("heroAlertsIcon"); var cardSunRise = document.getElementById("cardSunRise"); var cardSunSet = document.getElementById("cardSunSet"); var cardLocalTime = document.getElementById("cardLocalTime"); var cardLocalDate = document.getElementById("cardLocalDate"); var cardPressure = document.getElementById("cardPressure"); var cardHumidty = document.getElementById("cardHumidity"); var cardHumidityWater = document.getElementById("cardHumidityWater"); //var cardDewPoint = document.getElementById("cardDewPOint"); var cardWindSpeed = document.getElementById("cardWindSpeed"); var cardWindDirection2 = document.getElementById("cardWindDirection2"); var cardWindDirectionArrow = document.getElementById("cardWindDirectionArrow"); var cardForecastWeekday0 = document.getElementById("cardForecastWeekday0"); var cardForecastMin0 = document.getElementById("cardForecastMin0"); var cardForecastMax0 = document.getElementById("cardForecastMax0"); var cardForecastTempNow0 = document.getElementById("cardForecastTempNow0"); var cardForecastTempMin0 = document.getElementById("cardForecastTempMin0"); var cardForecastTempMax0 = document.getElementById("cardForecastTempMax0"); var cardForecastWeekday1 = document.getElementById("cardForecastWeekday1"); var cardForecastMin1 = document.getElementById("cardForecastMin1"); var cardForecastMax1 = document.getElementById("cardForecastMax1"); var cardForecastTempNow1 = document.getElementById("cardForecastTempNow1"); var cardForecastTempMin1 = document.getElementById("cardForecastTempMin1"); var cardForecastTempMax1 = document.getElementById("cardForecastTempMax1"); var cardForecastWeekday2 = document.getElementById("cardForecastWeekday2"); var cardForecastMin2 = document.getElementById("cardForecastMin2"); var cardForecastMax2 = document.getElementById("cardForecastMax2"); var cardForecastTempNow2 = document.getElementById("cardForecastTempNow2"); var cardForecastTempMin2 = document.getElementById("cardForecastTempMin2"); var cardForecastTempMax2 = document.getElementById("cardForecastTempMax2"); var cardForecastWeekday3 = document.getElementById("cardForecastWeekday3"); var cardForecastMin3 = document.getElementById("cardForecastMin3"); var cardForecastMax3 = document.getElementById("cardForecastMax3"); var cardForecastTempNow3 = document.getElementById("cardForecastTempNow3"); var cardForecastTempMin3 = document.getElementById("cardForecastTempMin3"); var cardForecastTempMax3 = document.getElementById("cardForecastTempMax3"); var cardForecastWeekday4 = document.getElementById("cardForecastWeekday4"); var cardForecastMin4 = document.getElementById("cardForecastMin4"); var cardForecastMax4 = document.getElementById("cardForecastMax4"); var cardForecastTempNow4 = document.getElementById("cardForecastTempNow4"); var cardForecastTempMin4 = document.getElementById("cardForecastTempMin4"); var cardForecastTempMax4 = document.getElementById("cardForecastTempMax4"); var cardUV = document.getElementById("cardUV"); var cardUVPoint = document.getElementById("cardUVPoint"); var cardUVTitle = document.getElementById("cardUVTitle"); var probPrecipitacao = document.getElementById("probPrecipitacao"); var cardMoonIcon = document.getElementById("cardMoonIcon"); var cardMoonDescription = document.getElementById("cardMoonDescription"); var moons = {}; moons["Waxing Gibbous"] = { name: "Lua Crescente", icon: "waxing-gibbous.png" }; moons["First Quarter"] = { name: "Quarto Crescente", icon: "first-quarter.png" }; moons["Full Moon"] = { name: "Lua Cheia", icon: "full-moon.png" }; moons["Waning Gibbous"] = { name: "Lua Minguante", icon: "waning-gibbous.png" }; moons["Last Quarter"] = { name: "Quarto Minguante", icon: "last-quarter.png" }; moons["New Moon"] = { name: "Lua Nova", icon: "new-moon.png" }; moons["Waxing Crescent"] = { name: "Quarto Crescente", icon: "waxing-crescent.png" }; moons["Waning Crescent"] = { name: "Quarto Minguante", icon: "waning-crescent.png" }; addlog('end mass getElementById'); const distritos = []; distritos['Aveiro'] = 1; distritos['Beja'] = 2; distritos['Braga'] = 3; distritos['Bragança'] = 4; distritos['Castelo Branco'] = 5; distritos['Coimbra'] = 6; distritos['Évora'] = 7; distritos['Faro'] = 8; distritos['Guarda'] = 9; distritos['Leiria'] = 10; distritos['Lisboa'] = 11; distritos['Portalegre'] = 12; distritos['Porto'] = 13; distritos['Santarém'] = 14; distritos['Setúbal'] = 15; distritos['Viana do Castelo'] = 16; distritos['Vila Real'] = 17; distritos['Viseu'] = 18; distritos['Funchal'] = 31; distritos['Porto Santo'] = 32; distritos['Vila do Porto'] = 41; distritos['Ponta Delgada'] = 42; distritos['Hangra do Heroísmo'] = 43; distritos['Santa Cruz da Graciosa'] = 44; distritos['Velas'] = 45; distritos['Madalena'] = 46; distritos['Horta'] = 47; distritos['Santa Cruz das Flores'] = 48; distritos['Vila do Corvo'] = 49; const areaAvisoDB = [ { idDistrito: 1, idAreaAviso: 'AVR' }, { idDistrito: 2, idAreaAviso: 'BJA' }, { idDistrito: 3, idAreaAviso: 'BRG' }, { idDistrito: 4, idAreaAviso: 'BGC' }, { idDistrito: 5, idAreaAviso: 'CBO' }, { idDistrito: 6, idAreaAviso: 'CBR' }, { idDistrito: 7, idAreaAviso: 'EVR' }, { idDistrito: 8, idAreaAviso: 'FAR' }, { idDistrito: 8, idAreaAviso: 'FAR' }, { idDistrito: 9, idAreaAviso: 'GDA' }, { idDistrito: 10, idAreaAviso: 'LRA' }, { idDistrito: 11, idAreaAviso: 'LSB' }, { idDistrito: 12, idAreaAviso: 'PTG' }, { idDistrito: 13, idAreaAviso: 'PTO' }, { idDistrito: 14, idAreaAviso: 'STM' }, { idDistrito: 15, idAreaAviso: 'STB' }, { idDistrito: 16, idAreaAviso: 'VCT' }, { idDistrito: 17, idAreaAviso: 'VRL' }, { idDistrito: 18, idAreaAviso: 'VIS' }, { idDistrito: 31, idAreaAviso: 'MCS' }, { idDistrito: 32, idAreaAviso: 'MPS' }, { idDistrito: 41, idAreaAviso: 'AOR' }, { idDistrito: 42, idAreaAviso: 'AOR' }, { idDistrito: 43, idAreaAviso: 'ACE' }, { idDistrito: 44, idAreaAviso: 'ACE' }, { idDistrito: 45, idAreaAviso: 'ACE' }, { idDistrito: 46, idAreaAviso: 'ACE' }, { idDistrito: 47, idAreaAviso: 'ACE' }, { idDistrito: 48, idAreaAviso: 'AOC' }, { idDistrito: 49, idAreaAviso: 'AOC' } ]; const weekDays = ["DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SAB"]; const estadoTempo = []; estadoTempo['Thunderstorm'] = 'Trovoada'; estadoTempo['Drizzle'] = 'Chuva Ligeira'; estadoTempo['Rain'] = 'Chuva'; estadoTempo['Snow'] = 'Neve'; estadoTempo['Mist'] = 'Nelina'; estadoTempo['Smoke'] = 'Fumo'; estadoTempo['Haze'] = 'Granizo'; estadoTempo['Dust'] = 'Poeiras'; estadoTempo['Fog'] = 'Nevoeiro'; estadoTempo['Sand'] = 'Areia'; estadoTempo['Ash'] = 'Cinza'; estadoTempo['Squall'] = 'Rajadas de Vento'; estadoTempo['Tornado'] = 'Tornado'; estadoTempo['Clear'] = 'Céu Limpo'; estadoTempo['Clouds'] = 'Nuvens'; addlog('end mass array declaration'); var coords; function getAreaAvisoByIdDistrito(idDistrito) { const foundItem = areaAvisoDB.find(item => item.idDistrito === idDistrito); if (foundItem) { return foundItem.idAreaAviso; } else { return null; } } function isNowBetween(startTimeString, endTimeString) { const now = new Date(); const startTime = new Date(startTimeString); const endTime = new Date(endTimeString); return now >= startTime && now <= endTime; } function getLocation() { /* return new Promise((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(resolve, reject); } else { reject("Geolocation is not supported by this browser."); } }); */ // 1. Check for cached coordinates const cachedCoordinates = localStorage.getItem('coordinates'); if (cachedCoordinates) { coords = JSON.parse(cachedCoordinates); //displayLocation(coords.latitude, coords.longitude, "Cached Coordinates"); // You can start your code execution here with the cached coordinates getAndDisplayLocation(); } else { //displayLocation(null, null, "No Cached Coordinates"); } // 2. Get approximate location (fallback) if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { const { latitude, longitude } = position.coords; //displayLocation(latitude, longitude, "Approximate Location"); }, (error) => { console.error("Error getting approximate location:", error); // Consider IP-based geolocation as a last resort here // (requires a third-party service) }, { enableHighAccuracy: false, timeout: 5000 } // Reduced accuracy and timeout ); // 3. Get precise location (and update) navigator.geolocation.getCurrentPosition( (position) => { const { latitude, longitude } = position.coords; localStorage.setItem('coordinates', JSON.stringify({ latitude, longitude })); // Cache coordinates //displayLocation(latitude, longitude, "Precise Location"); // Re-execute your code here with the precise coordinates getAndDisplayLocation(); }, (error) => { console.error("Error getting precise location:", error); }, { enableHighAccuracy: true, timeout: 10000 } // Higher accuracy and longer timeout ); } else { console.error("Geolocation is not supported by this browser."); } } function getDateTime() { const now = new Date(); const year = now.getFullYear(); const month = ('0' + (now.getMonth() + 1)).slice(-2); // Add leading zero if needed const day = ('0' + now.getDate()).slice(-2); // Add leading zero if needed const date = `${year}-${month}-${day}`; var hours = now.getHours(); const minutes = ('0' + now.getMinutes()).slice(-2); // Add leading zero if needed const time = `${hours}:${minutes}`; return { date, time }; } function extractTime(timestamp) { const date = new Date(timestamp * 1000); // Convert seconds to milliseconds var hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); const strTime = hours + ':' + (minutes < 10 ? '0' + minutes : minutes); return strTime; } function getWindDirectionAbbreviationPt(degrees) { const directions = [ "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSO", "SO", "OSO", "O", "ONO", "NO", "NNO" ]; const index = Math.round(degrees / 22.5) % 16; return directions[index]; } addlog('end functions declare'); //async function getAndDisplayLocation() { try { const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('lat') > 0) { clat = urlParams.get('lat'); clon = urlParams.get('lon'); } else { clat = coords.latitude; clon = coords.longitude; } //console.log(clat + ' ' + clon); //clat = 37.18921; //clon = -8.43822; // Do something with clat and clon addlog('1 enter getAndDisplayLocation'); //fetch(`https://json.geoapi.pt/gps/${clat},${clon}/base`).then(res => res.json()). // then(data => { /* fetch(`https://nominatim.openstreetmap.org/reverse.php?lat=${clat}&lon=${clon}&zoom=18&format=jsonv2`).then(res => res.json()).then(rdata => { if (rdata.address.city === undefined || rdata.address.city === null) { cidade = rdata.address.town; } else { cidade = rdata.address.city; concelho = rdata.address.municipality; distrito = rdata.address.county; } fetch(`https://json.geoapi.pt/gps/${clat},${clon}/base`).then(res => res.json()).then(geoapidata => { concelho = geoapidata.concelho; distrito = geoapidata.; }); */ fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${clat},${clon}&key=AIzaSyCfkuIqZhJzL__agrdxPVt_AaAoG1X5r2U`).then(res => res.json()).then(googledata => { const addressComponents = googledata.results[0].address_components; const adminAreaLevel2 = addressComponents.find(component => component.types.includes('administrative_area_level_2')); cidade = adminAreaLevel2.short_name; const adminAreaLevel1 = addressComponents.find(component => component.types.includes('administrative_area_level_1')); distrito = adminAreaLevel1.short_name.replace(' District', ''); distrito = distrito.replace('Distrito de ', ''); console.log('cidade:' + cidade + ' distrito:' + distrito); //distrito = 'Faro'; //cidade = 'Silves'; // store geo location in local storage localStorage.setItem('cidadeAtual', cidade); localStorage.setItem('concelhoAtual', concelho); localStorage.setItem('distritorAtual', distrito); localStorage.setItem('clatAtual', clat); localStorage.setItem('clonAtual', clon); //console.log(data); // get ipma globalIdLocal fetch('https://api.ipma.pt/open-data/distrits-islands.json').then(res => res.json()).then(data => { data.data.forEach(myFunction) function myFunction(itemDistricts, index, arr) { addlog('2 enter myFunction'); if (distritos[distrito] == itemDistricts.idDistrito) { idDistrito = distritos[distrito]; idAreaAviso = getAreaAvisoByIdDistrito(idDistrito); //console.log("idDistrito="+idDistrito + " idAreaAviso=" + idAreaAviso); // Store alert area for push notifications localStorage.setItem('idAreaAvisoAtual', idAreaAviso); // Silently update push subscription if already granted if (typeof window.updatePushAreaAviso === 'function') { window.updatePushAreaAviso(idAreaAviso); } //console.log('match ids = distrito:' + distrito + ' id distrito:' + distritos[distrito] + ' id item:' + itemDistricts.idDistrito); //console.log("item.globalIdLocal: " + itemDistricts.globalIdLocal); ipmaGlobalIdLocal = itemDistricts.globalIdLocal; fetch(`https://app.thesocialnerd.pt/m/s/globalIdLocal.json.php?globalIdLocal=${ipmaGlobalIdLocal}`).then(res => res.json()).then(data => { data.data.forEach(myFunction) function myFunction(item, index, arr) { var date = new Date(item.forecastDate); //console.log(item.forecastDate); if (index == 0) { //var date = new Date(item.forecastDate); cardForecastWeekday0.innerHTML = weekDays[date.getDay()]; cardForecastMin0.innerHTML = Math.round(item.tMin) + 'ºC'; cardForecastMax0.innerHTML = Math.round(item.tMax) + 'ºC'; cardForecastTempMin0.style.width = ((100*item.tMin)/40)-5 + "%"; cardForecastTempMax0.style.width = 95-(100*item.tMax)/40 + "%"; } else if (index == 1) { //var date = new Date(item.forecastDate); cardForecastWeekday1.innerHTML = weekDays[date.getDay()]; cardForecastMin1.innerHTML = Math.round(item.tMin) + 'ºC'; cardForecastMax1.innerHTML = Math.round(item.tMax) + 'ºC'; cardForecastTempMin1.style.width = ((100*item.tMin)/40)-5 + "%"; cardForecastTempMax1.style.width = 95-(100*item.tMax)/40 + "%"; } else if (index == 2) { //var date = new Date(item.forecastDate); cardForecastWeekday2.innerHTML = weekDays[date.getDay()]; cardForecastMin2.innerHTML = Math.round(item.tMin) + 'ºC'; cardForecastMax2.innerHTML = Math.round(item.tMax) + 'ºC'; cardForecastTempMin2.style.width = ((100*item.tMin)/40)-5 + "%"; cardForecastTempMax2.style.width = 95-(100*item.tMax)/40 + "%"; } else if (index == 3) { //var date = new Date(item.forecastDate); cardForecastWeekday3.innerHTML = weekDays[date.getDay()]; cardForecastMin3.innerHTML = Math.round(item.tMin) + 'ºC'; cardForecastMax3.innerHTML = Math.round(item.tMax) + 'ºC'; cardForecastTempMin3.style.width = ((100*item.tMin)/40)-5 + "%"; cardForecastTempMax3.style.width = 95-(100*item.tMax)/40 + "%"; } else if (index == 4) { //var date = new Date(item.forecastDate); cardForecastWeekday4.innerHTML = weekDays[date.getDay()]; cardForecastMin4.innerHTML = Math.round(item.tMin) + 'ºC'; cardForecastMax4.innerHTML = Math.round(item.tMax) + 'ºC'; cardForecastTempMin4.style.width = ((100*item.tMin)/40)-5 + "%"; cardForecastTempMax4.style.width = 95-(100*item.tMax)/40 + "%"; } } }) } else { //console.log('NO match ids = distrito:' + distrito + ' id distrito:' + distritos[distrito] + ' id item:' + itemDistricts.idDistrito); //console.log("item.globalIdLocal: " + itemDistricts.globalIdLocal); } } }) //console.log(ipmaGlobalIdLocal); // get ipma forecast //console.log(data) //fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cidade}&appid=${API_KEY}&units=${units}`).then(res => res.json()).then(data => { fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${clat}&lon=${clon}&appid=${API_KEY}&units=${units}`).then(res => res.json()).then(data => { cardForecastTempNow0.style.marginLeft = (100*data.main.temp)/40 + "%"; heroWeatherNowTemp.innerHTML = `${data.main.temp.toFixed()}°C`; heroWeatherNowLocation.innerHTML = cidade; heroWeatherNowDescription.innerHTML = estadoTempo[data.weather[0].main]; heroWeatherThermalSensation.innerHTML = `Sensação Térmica: ${data.main.feels_like.toFixed()}°C`; //heroWeatherTempMinMax.innerHTML = `Máx: ${data.main.temp_max.toFixed()}°C  Min: ${data.main.temp_min.toFixed()}°C`; cardSunRise.innerHTML = extractTime(data.sys.sunrise); cardSunSet.innerHTML = extractTime(data.sys.sunset); cardLocalTime.innerHTML = getDateTime().time; cardLocalDate.innerHTML = getDateTime().date; cardPressure.innerHTML = data.main.pressure + ' hPa'; const range = 1050 - 1000; const adjustedValue = data.main.pressure - 1000; const percentage = Math.abs((adjustedValue / range)); cardPressure.style.setProperty('--value', percentage); //console.log(cardPressure.style); cardHumidity.innerHTML = data.main.humidity + '%'; cardHumidityWater.style.height = (data.main.humidity - 20) + '%'; //cardHumidityWater.style.height = '90%'; cardWindSpeed.innerHTML = data.wind.speed; cardWindDirection2.innerHTML = getWindDirectionAbbreviationPt(data.wind.deg); cardWindDirectionArrow.style.transform = `rotate(${data.wind.deg}deg)`; }) fetch(`https://api.open-meteo.com/v1/forecast?latitude=${clat}&longitude=${clon}&hourly=temperature_2m,relative_humidity_2m,precipitation_probability,weather_code,pressure_msl,wind_speed_10m,wind_direction_10m&daily=temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,sunrise,sunset,uv_index_max,uv_index_clear_sky_max&timezone=auto&forecast_days=1`).then(res => res.json()).then(data => { const d = new Date(); let hour = d.getHours(); //console.log(data); //console.log(data.daily.temperature_2m_max[0]); heroWeatherTempMinMax.innerHTML = `Min: ${data.daily.temperature_2m_min[0]}°C  Máx: ${data.daily.temperature_2m_max[0]}°C`; cardUVTitle.innerHTML = 'UV Máximo Previsto'; cardUV.innerHTML = data.daily.uv_index_clear_sky_max; cardUVPoint.style.marginLeft = data.daily.uv_index_clear_sky_max * 5 + "%"; probPrecipitacao.innerHTML = data.hourly.precipitation_probability[hour] + "%"; }) fetch(`https://app.thesocialnerd.pt/m/weatherStations.json.php?weatherStation=fontes`).then(res => res.json()).then(data => { cardMoonDescription.innerHTML = moons[data.MoonPhaseStr].name; cardMoonIcon.src = '/m/i/moon/' + moons[data.MoonPhaseStr].icon; }) fetch(`https://app.thesocialnerd.pt/c/warnings_www.json`).then(res => res.json()).then(data => { data.forEach(myFwarnings) //console.log('avisos'); function myFwarnings(item, index, arr) { //console.log("item.idAreaAviso " + item.idAreaAviso + " / idAreaAviso " + idAreaAviso); if (item.idAreaAviso.trim() == idAreaAviso && item.awarenessLevelID.trim() != 'green') { //console.log('area match'); if (isNowBetween(item.startTime, item.endTime)) { //heroAlerts.style.display = 'block'; avisoDB[item['awarenessTypeName']] = item.awarenessLevelID; /* heroAlertsList.innerHTML = heroAlertsList.innerHTML + ' ' + item['awarenessTypeName'] + '
'; */ } } else { //heroAlerts.style.display = 'none'; } } if (Object.keys(avisoDB).length === 0) { heroAlertsList.innerHTML = '
Sem avisos
'; heroAlertsIcon.style.stroke = '#ffffff'; } else { heroAlertsList.innerHTML = ''; for(let aviso in avisoDB){ heroAlertsList.innerHTML = heroAlertsList.innerHTML + ' ' + aviso + '
'; } } }) }) } catch (error) { console.error("Error getting location:", error); } } getLocation();