Work on open-meteo api ahndling

This commit is contained in:
Pau Figueras 2023-02-06 21:25:31 +01:00
pare 2fb2986aa4
commit 7e735e6c1b
S'han modificat 6 arxius amb 101 adicions i 12 eliminacions

Veure arxiu

@ -2,7 +2,7 @@
import { NavbarObject } from "../classes/NavObject"; import { NavbarObject } from "../classes/NavObject";
import Navbar from "../components/navbar.svelte"; import Navbar from "../components/navbar.svelte";
let navbarElemenets: NavbarObject[] = [new NavbarObject('/', 'Home'), new NavbarObject('/aaaa', 'aaaa'), new NavbarObject('/test1', 'test1')] let navbarElemenets: NavbarObject[] = [new NavbarObject('/', 'Home'), new NavbarObject('/temps', 'Temps'), new NavbarObject('/xema', 'Estacions'), new NavbarObject('/openmeteo', 'Dades Open Meteo')]
</script> </script>
<Navbar navobjs={navbarElemenets} /> <Navbar navobjs={navbarElemenets} />
<slot /> <slot />

Veure arxiu

@ -0,0 +1,34 @@
const geocodingApiBase: string = "https://geocoding-api.open-meteo.com/v1/search";
const openMeteoApiBase: string = "https://api.open-meteo.com/v1/forecast";
let location: string = "L'Hospitalet de Llobregat";
let previousLocation = '';
export function load(): object {
let openMeteoData = getFromOpenMeteo(location);
let latitude: number = openMeteoData.then((data) => data.results[0].latitude);
let longitude: number = openMeteoData.then((data) => data.results[0].longitude);
let openMeteoWeather = getWeatherFromOpenMeteo(latitude, longitude);
return { location: openMeteoData.then( (data) => data.results[0].name ).catch( (_e) => previousLocation ), weatherData: openMeteoWeather, latitude, longitude }
};
function changeLocation(newLoc: string): void {
previousLocation = location;
location = newLoc;
}
export const actions = {
changeLoc: async ({ request }) => {
const data: FormData = await request.formData();
changeLocation(data.get('newloc'));
}
}
async function getFromOpenMeteo(ubicacio: string): Promise<any> {
let geoCodeResponse: Response = await fetch(`${geocodingApiBase}?name=${ubicacio}&count=1`);
return geoCodeResponse.json();
}
async function getWeatherFromOpenMeteo(latitude: any, longitude: any) {
let openMeteoResponse: Response = await fetch(`${openMeteoApiBase}?latitude=12&longitude=12`);
return openMeteoResponse.json()
}

Veure arxiu

@ -0,0 +1,28 @@
<script lang="ts">
import { enhance } from "$app/forms";
let display: string = 'none';
let loading: boolean = false;
export let data: any;
function toggleDisplay(): void {
display = (display === 'none') ? 'block' : 'none';
}
</script>
<div class="box" id="locChange" style="display: {display};">
<form action="?/changeLoc" method="post" use:enhance={ () => { loading = true; return async ( { update } ) => { await update(); loading = false; } } }>
<p>Change location</p>
<div class="schBox"><input type="text" placeholder="Change location" name='newloc' disabled={ loading }></div>
<button type="submit" disabled={loading}>Canviar</button>
</form>
</div>
<button type="button" on:click={toggleDisplay}>Canviar ubicació</button>
<pre>{ JSON.stringify(data) }</pre>
<footer>
<p>Dades provinents de:</p>
<ul>
<li><a href='https://meteo.cat' target="_blank" rel="noreferrer">Servei Meteorologic de Catalunya</a></li>
<li><a href='https://open-meteo.com' target="_blank" rel="noreferrer">Open-Meteo</a></li>
</ul>
</footer>

Veure arxiu

@ -1,15 +1,17 @@
const headers = { 'X-API-KEY': '1FvqqqUpoeNgNpxZQxJX6FBDLbwKscx5hgXhZxUb', 'Content-type': 'application/json' } const headers = { 'X-API-KEY': '1FvqqqUpoeNgNpxZQxJX6FBDLbwKscx5hgXhZxUb', 'Content-type': 'application/json' }
const geocodingApiBase: string = "https://geocoding-api.open-meteo.com/v1/search";
const openMeteoApiBase: string = "https://api.open-meteo.com/v1/forecast";
let location: string = "L'Hospitalet de Llobregat"; let location: string = "L'Hospitalet de Llobregat";
let municipis = await fetch('https://api.meteo.cat/referencia/v1/municipis', { method: 'GET', headers: new Headers(headers), credentials: 'include' }).then( (data) => data.json() ); let municipis = await fetch('https://api.meteo.cat/referencia/v1/municipis', { method: 'GET', headers: new Headers(headers), credentials: 'include' }).then( (data) => data.json() );
export function load(): { location: string, weatherData: Promise<any> } { export function load(): object {
let objMunicipi = getCityCode( location ); let objMunicipi = getCityCode( location );
if (objMunicipi === location) { if (objMunicipi === location) {
return { location, weatherData: getWeather(location).then( (data) => data.message ) } return { location, weatherData: getWeather(location).then( (data) => data.message ), openMeteoData: getFromOpenMeteo(location) }
} }
let codiMunicipi: string = objMunicipi.codi; let codiMunicipi: string = objMunicipi.codi;
let locFullName: string = objMunicipi.nom; let locFullName: string = objMunicipi.nom;
return { location: locFullName, weatherData: getWeather(codiMunicipi) } return { location: locFullName, weatherData: getWeather(codiMunicipi), openMeteoData: getFromOpenMeteo(location), consums: checkConsum() }
}; };
function changeLocation(newLoc: string): void { function changeLocation(newLoc: string): void {
@ -28,6 +30,11 @@ export const actions = {
} }
} }
async function checkConsum(): Promise<any> {
let response: Response = await fetchApi('https://api.meteo.cat/quotes/v1/consum-actual');
return response.json();
}
async function getWeather(codiMunicipi: string): Promise<any> { async function getWeather(codiMunicipi: string): Promise<any> {
if (codiMunicipi !== '') { if (codiMunicipi !== '') {
let response = await fetchApi(`https://api.meteo.cat/pronostic/v1/municipal/${codiMunicipi}`) let response = await fetchApi(`https://api.meteo.cat/pronostic/v1/municipal/${codiMunicipi}`)
@ -36,6 +43,13 @@ async function getWeather(codiMunicipi: string): Promise<any> {
return ''; return '';
} }
async function getFromOpenMeteo(ubicacio: string): Promise<any> {
let geoCodeResponse: Response = await fetch(`${geocodingApiBase}?name=${ubicacio}&count=1`);
// let coordinates: { latitude: Promise<number>, longitude: Promise<number> } = { latitude: geoCodeResponse.json().then( (data) => data[0].latitude ), longitude: geoCodeResponse.json().then( (data) => data[0].longitude )};
// let weatherData: Response = await fetch(`${openMeteoApiBase}?latitude=${coordinates.latitude}&longitude=${coordinates.longitude}&hourly=temperature_850hPa&models=best_match`);
return geoCodeResponse.json();
}
function getCityCode(locName: string): object | string { function getCityCode(locName: string): object | string {
let foundMunicipis: object[] = municipis.filter( municipi => municipi["nom"].toLowerCase().startsWith(locName.toLowerCase()) ) let foundMunicipis: object[] = municipis.filter( municipi => municipi["nom"].toLowerCase().startsWith(locName.toLowerCase()) )
if ( foundMunicipis.length > 0 ) { if ( foundMunicipis.length > 0 ) {

Veure arxiu

@ -1,26 +1,27 @@
<script lang="ts"> <script lang="ts">
import { enhance } from "$app/forms"; import { enhance } from "$app/forms";
let display: string = 'none'; let display: string = 'none';
let loading: boolean = false;
export let data: any; export let data: any;
function toggleDisplay(): void { function toggleDisplay(): void {
display = (display === 'none') ? 'block' : 'none'; display = (display === 'none') ? 'block' : 'none';
} }
$: variables = data.weatherData.dies[0].variables; // $: variables = data.weatherData.dies[0].variables;
</script> </script>
<div class="box" id="locChange" style="display: {display};"> <div class="box" id="locChange" style="display: {display};">
<form action="?/changeLoc" method="post" use:enhance> <form action="?/changeLoc" method="post" use:enhance={ () => { loading = true; return async ( { update } ) => { await update(); loading = false; } } }>
<p>Change location</p> <p>Change location</p>
<div class="schBox"><input type="text" placeholder="Change location" name='newloc'></div> <div class="schBox"><input type="text" placeholder="Change location" name='newloc' disabled={ loading }></div>
<button type="submit">Canviar</button> <button type="submit" disabled={loading}>Canviar</button>
</form> </form>
</div> </div>
<button type="button" on:click={toggleDisplay}>Canviar ubicació</button> <button type="button" on:click={toggleDisplay}>Canviar ubicació</button>
<p>El temps a: {data.location}</p> <p>El temps a: {data.location}</p>
<!-- <pre>{ JSON.stringify(data.weatherData) }</pre> --> <pre>{ JSON.stringify(data.weatherData) }</pre>
<table> <table>
<thead> <thead>
<tr> <tr>
@ -30,13 +31,22 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr> <!-- <tr>
<td>{ variables.tmax.valor }{ variables.tmax.unitat }</td> <td>{ variables.tmax.valor }{ variables.tmax.unitat }</td>
<td>{ variables.tmin.valor }{ variables.tmin.unitat }</td> <td>{ variables.tmin.valor }{ variables.tmin.unitat }</td>
<td>{ variables.precipitacio.valor }{ variables.precipitacio.unitat }</td> <td>{ variables.precipitacio.valor }{ variables.precipitacio.unitat }</td>
</tr> </tr> -->
</tbody> </tbody>
</table> </table>
<pre>{ JSON.stringify(data.openMeteoData) }</pre>
<pre>{ JSON.stringify(data.consums) ?? 'No consum available' }</pre>
<footer>
<p>Dades provinents de:</p>
<ul>
<li><a href='https://meteo.cat' target="_blank" rel="noreferrer">Servei Meteorologic de Catalunya</a></li>
<li><a href='https://open-meteo.com' target="_blank" rel="noreferrer">Open-Meteo</a></li>
</ul>
</footer>
<style> <style>
table { table {
border-collapse: collapse; border-collapse: collapse;

Veure arxiu

@ -0,0 +1,3 @@
<script type='ts'>
</script>
<p>xema ok</p>