CSS&JS/👀Study and Copy

[WDS]open meteo OPEN API로 현재 지역 날씨 알려주는 웹 만들기(클론코딩)

arancia_ 2023. 2. 2. 11:14

API 키를 발급 받지 않아도 되는 편리한 날씨 API : https://open-meteo.com/

 

Free Open-Source Weather API | Open-Meteo.com

$ curl "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41¤t_weather=true&hourly=temperature_2m,relativehumidity_2m,windspeed_10m" { "current_weather": { "time": "2022-01-01T15:00" "temperature": 2.4, "weathercode": 3, "windspeed": 11.9

open-meteo.com

데모 페이지 : https://ohikmyeong.github.io/wds-weather-app

소스 : https://github.com/OhIkmyeong/wds-weather-app

 

GitHub - OhIkmyeong/wds-weather-app: [WDS]How To Build A Weather App In JavaScript Without Needing A Server

[WDS]How To Build A Weather App In JavaScript Without Needing A Server - GitHub - OhIkmyeong/wds-weather-app: [WDS]How To Build A Weather App In JavaScript Without Needing A Server

github.com

navigator.geolocation.getCurrentPosition(성공시 콜백함수, 실패시 콜백함수)

Intl의 다양한 기능들 : 노마드 코더 영상 Intl에 대해 알아보기 

  • 현재 거주 시간대 가져오기 e) Asia/Seoul
Intl.DateTimeFormat().resolvedOptions().timeZone;
  • 밀리세컨드(timestamp)를 요일(day)로 변환
new Intl.DateTimeFormat("en-US", { weekday: "long" }).format(timestamp);
  • 밀리세컨드(timestamp)를 시간대(AM/PM)으로 변환
new Intl.DateTimeFormat("en-US", { hour: "numeric" }).format(timestamp);
const $clone = document.importNode($temp.content,true);
const $clone = $temp.content.cloneNode(true);
//.content를 하지 않으면 <template>부터 복사되기 때문에 에러 발생...
  • 구조 분해 할당에서 
const obj = { key : "value" };
function object_destructive({key}){
	return {key};  //이는 {key : key} 와 같다.
}
object_destructive(obj); // {key : "value"}

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How To Build A Weather App In JavaScript Without Needing A Server</title>
    <link rel="stylesheet" href="./css/style.css">
    <script src="./js/main.js" type="module"></script>
</head>
<body class="blur">
    <!--  -->
    <a href="https://www.youtube.com/watch?v=w0VEOghdMpQ&t=2411s" target="_blank">
        How To Build A Weather App In JavaScript Without Needing A Server by Web Dev Simplified
    </a>
    <!-- [CURR] -->
    <section id="wrap-curr">
        <article id="curr-left">
            <img src="./img/sun.svg" alt="날씨 아이콘" title="weather icon" class="ic" data-curr-icon>
            <div class="val-temp" data-curr-temp>00</div>
        </article>
 
        <ul id="curr-right">
            <li>
                <p class="lbl">high</p>
                <div class="val-temp" data-curr-high>00</div>
            </li>
            <li>
                <p class="lbl">fl high</p>
                <div class="val-temp" data-curr-high-fl>00</div>
            </li>
            <li>
                <p class="lbl">wind</p>
                <div class="val-wind" data-curr-wind>00</div>
            </li>
            <li>
                <p class="lbl">low</p>
                <div class="val-temp" data-curr-low>00</div>
            </li>
            <li>
                <p class="lbl">fl low</p>
                <div class="val-temp" data-curr-low-fl>00</div>
            </li>
            <li>
                <p class="lbl">precip</p>
                <div class="val-inch" data-curr-prcp>00</div>
            </li>
        </ul>
    </section><!-- wrap-curr -->
 
    <!-- [DAYS] -->
    <section id="wrap-days">
        <template>
            <article class="day-card">
                <img src="./img/sun.svg" alt="" class="ic" data-days-ic>
                <p class="lbl" data-days-day>WednesDay</p>
                <div class="val-temp" data-days-temp>32</div>
            </article>
        </template>  
    </section><!-- wrap-days -->
 
    <!-- [HOURS] -->
    <table id="tbl-hours">
        <caption>시간대별</caption>
        <colgroup>
            <col>
            <col style="width:100px;">
            <col style="width:100px;">
            <col style="width:100px;">
            <col style="width:100px;">
            <col style="width:100px;">
        </colgroup>
        <tbody>
            <template>
                <tr>
                    <td>
                        <p class="lbl" data-hourly-day>MONDAY</p>
                        <p class="val-time" data-hourly-hour>3</p>
                    </td>
                    <td>
                        <img src="./img/sun.svg" alt="" class="ic" data-hourly-ic>
                    </td>
                    <td>
                        <p class="lbl">TEMP</p>
                        <div class="val-temp" data-hourly-temp>31</div>
                    </td>
                    <td>
                        <p class="lbl">FL TEMP</p>
                        <div class="val-temp"data-hourly-temp-fl>25</div>
                    </td>
                    <td>
                        <p class="lbl">wind</p>
                        <div class="val-wind" data-hourly-wind>25</div>
                    </td>
                    <td>
                        <p class="lbl">PRECIP</p>
                        <div class="val-prcp" data-hourly-prcp>25</div>
                    </td>
                </tr>
            </template>
        </tbody>
    </table><!-- tbl-hours -->
</body>
</html>
cs

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
@charset "utf-8";
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700&display=swap');
:root{
    --f-fam:'Outfit', sans-serif;
    --bg : hsl(200,60%,70%);
    --bg-cell : hsl(200,100%,85%);
    --f1: hsl(200,100%,10%);
    --f2 :hsl(200,100%,25%);
}
 
*{margin:0;padding:0;box-sizing:border-box;}
li{list-style-type:none;} img{vertical-align:middle;}
 
body{
    background:var(--bg);
    font-family:var(--f-fam); font-size:18px; color:var(--f1);
    transition:filter .3s .3s linear;
}
 
.blur{
    filter:blur(20px);
    overflow:hidden;
}
 
a{
    display:block;
    padding:1em;
    background:var(--f1);
    text-align:center; font-size:13px; color:var(--bg);
    text-decoration:none;
}
 
/* 📌 [공통] */
.lbl{
    text-transform:uppercase;
    font-weight:600; font-size:.8em; color:var(--f2);
}
 
/* 📌 유닛 */
.val-unit{
    margin-left:.2em;
    font-size:.7em;
}
 
/* 📌 [CURRENT] */
#wrap-curr{
    display:flex;flex-flow:row wrap;
    justify-content:center;align-items:center; 
    gap:20px 40px;
    position:relative;
    max-width:calc(100% - 40px);
    padding:40px 20px; margin:20px auto;
    background:var(--bg-cell);
    border:2px solid var(--f1); border-radius:20px;
}
 
/* left */
#curr-left{
    display:flex; flex-flow:row wrap;
    justify-content:center;align-items:center;
    gap:0 20px;
    position:relative;
    text-align:center;
}
[data-curr-icon]{
    width:100px; aspect-ratio:1/1;
}
[data-curr-temp]{
    font-size:80px;
}
/* right */
#curr-right{
    display:flex; flex-flow:row wrap;
    justify-content:center; align-items:center;
    gap:10px 0;
    position:relative;
    text-align:center;
}
#curr-right > li{
    /* outline:1px solid red; */
    position:relative;
    padding:0 20px;
    border-left:1px solid hsl(200,100%,40%);
    text-align:center;
}
    #curr-right > li:first-child{
        border-left:none;
    }
 
#curr-right [class ^= "val-"]:not(.val-unit){
    font-size:1.5rem;
}
 
/* 📌 [DAYS] */
/* wrap */
#wrap-days{
    display:grid;
    grid-template-columns: repeat(auto-fit,120px);
    justify-content:center;
    gap:20px;
    position:relative;
    width:calc(100% - 40px);
    margin:20px auto;
}
/* card */
.day-card{
    position:relative;
    padding:15px 10px;
    background:var(--bg-cell);
    border:2px solid var(--f2); border-radius:10px;
    text-align:center;
}
.day-card .ic{
    width:50px; height:50px; object-fit:contain;;
}
.day-card .lbl{
    margin:10px 0 0px;
}
.day-card .val-temp{
    font-size:1.4rem;
}
/* 📌 [HOURS] */
#tbl-hours{
    table-layout:fixed;
    border-spacing:2px 10px; border-collapse:separate;
    position:relative;
    width:100%;
    text-align:center;
}
caption{display:none;}
 
#tbl-hours tr:nth-child(odd){
    background:hsl(200,100%,92%);;
}
#tbl-hours tr:nth-child(even){
    background:hsl(200,100%,90%);;
}
#tbl-hours td{
    padding:10px;
}
 
/* 시간 */
#tbl-hours .val-time{
    font-size:2rem;
}
.val-time-am::after,
.val-time-pm::after{
    margin-left:.1em;
    font-size:0.6em; font-weight:500; color:var(--f2);
}
.val-time-am::after{
    content:"AM"
}
.val-time-pm::after{
    content:'PM'
}
/* 아이콘 */
#tbl-hours .ic{
    width:40px;
}
cs

main.js

1
2
3
4
(async function (){
    const API = new WeatherAPI();
    await API.init();
})()
cs

iconMap.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export const ICON_MAP = new Map();
 
function add_map(values,name){
    values.forEach(val => {
        ICON_MAP.set(val,name);
    });
}//add_map
 
add_map([0,1], "sun");
add_map([2], "cloud-sun");
add_map([3], "cloud");
add_map([45,48], "smog");
add_map([51,53,55,56,57,61,63,65,66,67,80,81,82], "cloud-showers-heavy");
add_map([71,73,75,77,85,86], "snow");
add_map([95,96,99], "cloud-bold");
cs

Weather.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import { ICON_MAP } from "./iconMap.js";
 
export class WeatherAPI {
    constructor() {
        this.urlFull = 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,apparent_temperature,precipitation,weathercode,windspeed_10m&daily=weathercode,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,precipitation_sum&current_weather=true&timeformat=unixtime&timezone=Asia%2FTokyo';
    }//constructor
 
    /** init */
    async init(){
        navigator.geolocation.getCurrentPosition(this.success, this.fail);
    }//init
    
    /** 좌표 받아오는거 성공했을시 */
    success = async ({coords}) => {
        const {latitude:lat, longitude:lon} = coords;
        const timezone = this.get_time_zone();
        console.log(lat,lon,timezone);
        const data = await this.get_weather(lat,lon,timezone);
        if(!data) return;
        const APP = new WeatherApp();
        APP.init(data);
    }
 
    /** 좌표 받기 실패 */
    fail = e =>{
        console.error("위치 정보 받아오기 실패. 위치정보활성화를 해주세요. There was an error getting your location. Please allow us to use your location and refresh the page");
        document.body.innerHTML = '';
    }
 
    /** get time zone
     * @returns {String} ex: Asia/Seoul
     */
    get_time_zone() {
        return Intl.DateTimeFormat().resolvedOptions().timeZone;
    }//get_time_zone
 
    /**
     * get weather data
     * @param {Number} lat 
     * @param {Number} lon 
     * @param {String} timezone 
     * @returns {Object}parsed json data
     */
    get_weather(lat, lon, timezone) {
        const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&hourly=temperature_2m,apparent_temperature,precipitation,weathercode,windspeed_10m&daily=weathercode,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,precipitation_sum&current_weather=true&timeformat=unixtime&timezone=${timezone}`;
        return fetch(url)
            .then(res => res.json())
            .then(data => {
                console.log('full data', data);
                return {
                    current: this.parse_curr_weather(data),
                    daily: this.parse_daily_weather(data),
                    hourly: this.parse_hourly_weather(data),
                }
            })
            .catch(e=>{
                console.error(e);
                alert('Error');
            });
    }//get_weather
 
    /**
     * parse curr data
     * @param {Object} data 
     * @returns {Object}
     */
    parse_curr_weather({ current_weather, daily }) {
        const {
            temperature: currentTemp,
            weathercode: iconCode,
            windspeed: windSpeed
        } = current_weather;
 
        const {
            temperature_2m_max: [maxTemp],
            temperature_2m_min: [minTemp],
            apparent_temperature_max: [maxFeelsLike],
            apparent_temperature_min: [minFeelsLike],
            precipitation_sum: [precip]
        } = daily; //각 array의 첫번째 값만 필요하거든
 
        return {
            currentTemp: String(Math.round(currentTemp)).padStart(2"0"),
            highTemp: maxTemp,
            lowTemp: minTemp,
            highFeelsLike: maxFeelsLike,
            lowFeelsLike: minFeelsLike,
            windSpeed,
            precip: precip,
            iconCode
        }
    }//parse_curr_weather
 
    /**
     * parse daily data
     * @param {Object} data      
     * @returns {Object}
     */
    parse_daily_weather({ daily }) {
        const { time, weathercode, temperature_2m_max } = daily;
        return time.map((t, idx) => {
            return {
                timestamp: t * 1000,
                iconCode: weathercode[idx],
                maxTemp: Math.round(temperature_2m_max[idx])
            }
        });
    }//parse_daily_weather
 
    /**
     * parse hourly data
     * @param {Object} data 
     * @returns {Object}
     */
    parse_hourly_weather({ hourly, current_weather }) {
        const { time, weathercode, temperature_2m, apparent_temperature, windspeed_10m, precipitation } = hourly;
 
        const { time: currTime } = current_weather;
 
        return time
            .filter(t => t >= currTime)
            .map((t, idx) => {
                return {
                    timestamp: t * 1000,
                    iconCode: weathercode[idx],
                    temp: Math.round(temperature_2m[idx]),
                    feelsLike: Math.round(apparent_temperature[idx]),
                    windSpeed: Math.round(windspeed_10m[idx]),
                    precip: Math.round((precipitation[idx] * 100/ 100),
                }
            });
    }//parse_hourly_weather
}//WeatherAPI
 
/* ====================================== */
export class WeatherApp {
    /**
     * 실제로 화면을 그리기 시작함
    */
    constructor() {
    }//constructor
 
    /** 
     * 화면을 그리기 시작합니다 
     * @param {Object} data 
     * */
    init(data) {
        const { current, daily, hourly } = data;
        this.render_curr(current);
        this.render_daily(daily);
        this.render_hourly(hourly);
 
        document.body.classList.remove('blur');
    }//init
 
    /** 해당 dom에 textContent를 변경해준다
     * @param {String}selector
     * @param {String}value
     * @param {DOM}parent
     */
    set_value(selector, value, { parent = document } = {}) {
        const $dom = parent.querySelector(`[data-${selector}`);
        $dom.textContent = value;
        return $dom;
    }//set_value
 
    /**
     * iconCode에 맞춰 맞는 svg이미지 url을 가져옴
     * @param {Number}iconCode
     */
    get_icon_url(iconCode) {
        return `./img/${ICON_MAP.get(iconCode)}.svg`;
    }//get_icon_url
 
    /** 
     * timestamp를 요일로 바꿔준다
     * @param {Number} timestamp
     * @url https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
     */
    day_formatter(timestamp) {
        return new Intl.DateTimeFormat("en-US", { weekday: "long" }).format(timestamp);
    }//day_formatter
 
    /**
     * timestamp를 시간대로 바꿔준다
    */
    time_formatter(timestamp) {
        return new Intl.DateTimeFormat("en-US", { hour: "numeric" }).format(timestamp);
    }//time_formatter
    /**
     * 현재 날씨
     * @param {Object}data
     */
    render_curr(data) {
        // console.log(data);
        const $wrap = document.getElementById('wrap-curr');
        const $img = $wrap.querySelector('.ic');
 
        const { currentTemp, highFeelsLike, highTemp, iconCode, lowFeelsLike, lowTemp, precip, windSpeed } = data;
 
        this.set_value('curr-temp', currentTemp);
        this.set_value('curr-high', highTemp);
        this.set_value('curr-high-fl', highFeelsLike);
        this.set_value('curr-wind', windSpeed);
        this.set_value('curr-low', lowTemp);
        this.set_value('curr-low-fl', lowFeelsLike);
        this.set_value('curr-prcp', precip);
        $img.src = this.get_icon_url(iconCode);
 
        const $$val = $wrap.querySelectorAll('[class ^= "val-"]');
        $$val.forEach(this.add_unit);
    }//render_curr
 
    /**
     * 주간 날씨
     * @param {Object}data
     */
    render_daily(data) {
        const $wrap = document.getElementById('wrap-days');
        const $temp = $wrap.querySelector('template');
        const $frag = document.createDocumentFragment();
 
        data.forEach(daily => {
            const { timestamp, iconCode, maxTemp } = daily;
            const $clone = $temp.content.cloneNode(true);
 
            const $img = $clone.querySelector('[data-days-ic]');
            $img.src = this.get_icon_url(iconCode);
 
            this.set_value('days-day'this.day_formatter(timestamp), { parent: $clone });
 
            const $tempDaily = this.set_value('days-temp', maxTemp, { parent: $clone });
            this.add_unit($tempDaily);
 
            $frag.appendChild($clone);
        });
 
        $wrap.innerHTML = '';
        $wrap.appendChild($frag);
        console.log(data);
    }//render_daily
 
    /**
     * 시간별 날씨
     * @param {Object}data
     */
    render_hourly(data) {
        console.log(data);
        const $table = document.getElementById('tbl-hours');
        const $tbody = $table.getElementsByTagName('TBODY')[0];
        const $temp = $tbody.querySelector('TEMPLATE');
        const $frag = document.createDocumentFragment();
 
        data.forEach(obj => {
            const { timestamp, iconCode, temp, feelsLike, windSpeed, precip } = obj;
            const $clone = $temp.content.cloneNode(true);
            const $img = $clone.querySelector('[data-hourly-ic');
            $img.src = this.get_icon_url(iconCode);
            this.set_value("hourly-day",this.day_formatter(timestamp),{parent:$clone});
            this.set_value("hourly-hour",this.time_formatter(timestamp), { parent: $clone })
            this.add_unit(this.set_value("hourly-temp", temp, { parent: $clone }));
            this.add_unit(this.set_value("hourly-temp-fl", feelsLike, { parent: $clone }));
            this.add_unit(this.set_value("hourly-wind", windSpeed, { parent: $clone }));
            this.add_unit(this.set_value("hourly-prcp", precip, { parent: $clone }));
            $frag.appendChild($clone);
        });
 
        $tbody.innerHTML = '';
        $tbody.appendChild($frag);
    }//render_hourly
 
    /**
     * @param {DOM} $dom
     */
    add_unit($dom) {
        const type = $dom.classList[0].split('-')[1];
        const $sup = document.createElement('SPAN');
        $sup.classList.add('val-unit');
 
        switch (type) {
            case "temp":
                // $sup.innerHTML =  '&deg;'; //Farenheit
                $sup.innerHTML = '°C';
                break;
            case "wind":
                $sup.innerHTML = 'km/h';
                break;
            case "prcp":
                $sup.innerHTML = 'in';
                break;
            case "inch":
                $sup.innerHTML = 'inch';
                break;
            defaultbreak;
        }
        $dom.appendChild($sup);
    }//add_unit
}//WeatherApp
cs