From 957e4cc77cdb7e4857279cf61eb3eb214670c5af Mon Sep 17 00:00:00 2001 From: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> Date: Thu, 27 Oct 2022 21:15:38 +0530 Subject: [PATCH] feat(demo): add open weather API for real data Signed-off-by: Vinayak Kulkarni <19776877+vinayakkulkarni@users.noreply.github.com> --- .github/workflows/demo.yml | 2 ++ example/src/main.ts | 59 ++++++++++++++++++++++++++++---------- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/.github/workflows/demo.yml b/.github/workflows/demo.yml index d8c5b1e7..8fdf3bdb 100644 --- a/.github/workflows/demo.yml +++ b/.github/workflows/demo.yml @@ -30,6 +30,8 @@ jobs: - name: Run build 🏁 run: npm run build + env: + VITE_WEATHER_API_KEY: ${{ secrets.WEATHER_API_KEY }} - name: Deploy to GitHub Pages 🚀 uses: peaceiris/actions-gh-pages@v3.9.0 diff --git a/example/src/main.ts b/example/src/main.ts index db333d89..839161fb 100644 --- a/example/src/main.ts +++ b/example/src/main.ts @@ -11,22 +11,51 @@ const map = new mapboxgl.Map({ zoom: 9, }); -map.on('load', () => { +map.on('load', async () => { + const startingLatitude = -80; + const startingLongitude = -180; + const endingLatitude = 80; + const endingLongitude = 180; + const n = 10; + const points = []; + + for (let i = 0; i < n; i += 1) { + for (let j = 0; j < n; j += 1) { + points.push({ + lat: startingLatitude + (i * (endingLatitude - startingLatitude)) / n, + lng: + startingLongitude + (j * (endingLongitude - startingLongitude)) / n, + val: 0, + }); + } + } + + const baseUrl = + 'https://api.openweathermap.org/data/2.5/weather?units=metric'; + const apiKey = import.meta.env.VITE_WEATHER_API_KEY; + const urls = points.map( + ({ lat, lng }) => `${baseUrl}&lat=${lat}&lon=${lng}&appid=${apiKey}`, + ); + + const weathers = await Promise.all( + urls.map(async (url) => { + const response = await fetch(url); + return response.json(); + }), + ); + + points.forEach((point, index) => { + point.val = weathers.at(index).main.temp; + }); + const options = { + data: points, id: 'temperature', - data: [ - { - lat: 62.470663, - lon: 6.176846, - val: 16, - }, - { - lat: 48.094903, - lon: -1.371596, - val: 20, - }, - ], - } as MapboxInterpolateHeatmapLayer; - const layer = new MapboxInterpolateHeatmapLayer(options); + } as unknown; + + const layer = new MapboxInterpolateHeatmapLayer( + options as MapboxInterpolateHeatmapLayer, + ); + map.addLayer(layer); });