뚜피치의 개발공부

기상청 오픈API를 활용하여 전국 날씨 나타내주기(feat.JavaScript) 본문

개발공부

기상청 오픈API를 활용하여 전국 날씨 나타내주기(feat.JavaScript)

뚜피치 2019. 1. 26. 04:11

기상청 오픈API를 활용하여 전국 날씨를 나타내주기


오랜만에 포스팅! 오늘은 기상청 오픈API를 활용하여서 날씨를 띄워주는것을 리뷰해볼 예정이다.



사진 상 우측에 위치한 날씨를 표시해주는 것이다.

사용된 API의 링크는 https://www.data.go.kr/dataset/15000099/openapi.do <-여기!

언어는 javascript를 활용하여 구현해보았다. 일단 전체적인 코드를 본다면, script부분은

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
$(document).ready(function() {
                            var arr = [];
                            var today = new Date();
                            var week = new Array('일''월''화''수''목''금''토');
                            var year = today.getFullYear();
                            var month = today.getMonth() + 1;
                            var day = today.getDate();
                            var hours = today.getHours();
                            var minutes = today.getMinutes();
                            var hours_al = new Array('02''05''08''11''14''17''20''23');
                            var korea = [ {'region' : '서울','nx' : 60,'ny' : 127}, 
                                {'region' : '인천','nx' : 55,'ny' : 124}, 
                                {'region' : '경기도','nx' : 60,'ny' : 121}, 
                                {'region' : '강원도','nx' : 92,'ny' : 131}, 
                                {'region' : '충청북도','nx' : 69,'ny' : 106}, 
                                {'region' : '충청남도','nx' : 68,'ny' : 100},
                                {'region' : '전라북도','nx' : 63,'ny' : 89}, 
                                {'region' : '전라남도','nx' : 50,'ny' : 67}, 
                                {'region' : '경상남도','nx' : 90,'ny' : 77}, 
                                {'region' : '경상북도','nx' : 91,'ny' : 106}, 
                                {'region' : '제주도','nx' : 52,'ny' : 38} ];
 
                            /* $('.weather-date').html(
                                    month + "월 " + day + "일 "
                                            + week[today.getDay()] + "요일"); */
 
                            /* 동네예보 시간이 0200 0500 ... 3시간 단위로 23시까지 */
                            for (var i = 0; i < hours_al.length; i++) {
                                var h = hours_al[i] - hours;
                                if (h == -1 || h == 0 || h == -2) {
                                    var now = hours_al[i];
                                }
                                if (hours == 00) {
                                    var now = hours_al[7];
                                }
                            }
 
                            /* example
                             * 9시 -> 09시 변경 필요
                             */
                            if (hours < 10) {
                                hours = '0' + hours;
                            }
                            if (month < 10) {
                                month = '0' + month;
                            }
                            if (day < 10) {
                                day = '0' + day;
                            }
 
                            today = year + "" + month + "" + day;
 
                            /* 좌표 */
                            $.each(korea,function(j, k) {
                                                var _nx = korea[j].nx, _ny = korea[j].ny, region = korea[j].region, 
                                                apikey = "개별 api키"
                                                ForecastGribURL = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastSpaceData";
                                                ForecastGribURL += "?ServiceKey=" + apikey;
                                                ForecastGribURL += "&base_date=" + today;
                                                ForecastGribURL += "&base_time=" + now + "00";
                                                ForecastGribURL += "&nx=" + _nx + "&ny=" + _ny;
                                                arr.push({'url' : ForecastGribURL, 'region' : region});
 
                                                $.ajax({
                                                            url : arr[j].url,
                                                            type : 'GET',
                                                            success : function(data) {
                                                                var $data = $(data).find("response>body>items>item");
                                                                var cate = '';
                                                                var temp = '';
                                                                var sky = '';
                                                                var rain = '';
 
                                                                $.each($data,function(i,o) {
                                                                                    cate = $(o).find("category").text(); // 카테고리 목록    
 
                                                                                    if (cate == 'T3H') {
                                                                                        temp = $(this).find("fcstValue").text(); // 3시간 온도
                                                                                    }
                                                                                    if (cate == 'SKY') {
                                                                                        sky = $(this).find("fcstValue").text(); // 하늘상태
                                                                                    }
                                                                                    if (cate == 'PTY') {
                                                                                        rain = $(this).find("fcstValue").text(); // 강수형태
                                                                                    }
                                                                                });
 
                                                                $('.weather').append('<li class="list-group-item weather_li'+j+'"></li>');
                                                                $('.weather_li' + j).addClass('in' + j);
                                                                $('.in' + j).html(temp + " ℃"); //온도 
                                                                $('.in' + j).prepend(arr[j].region + '&emsp;'); // 지역이름
 
                                                                if (rain != 0) {
                                                                    switch (rain) {
                                                                    case '1':
                                                                        $('.in' + j).append(" / 비");
                                                                        $('.in' + j).prepend('<i class="fas fa-cloud-showers-heavy"></i>&emsp;');
                                                                        break;
                                                                    case '2':
                                                                        $('.in' + j).append(" / 비/눈");
                                                                        $('.in' + j).prepend('<i class="fas fa-cloud-rain"></i>&emsp;');
                                                                        break;
                                                                    case '3':
                                                                        $('.in' + j).append(" / 눈");
                                                                        $('.in' + j).prepend('<i class="fas fa-snowflake"></i>&emsp;');
                                                                        break;
                                                                    }
                                                                } else {
                                                                    switch (sky) {
                                                                    case '1':
                                                                        $('.in' + j).append(" / 맑음");
                                                                        $('.in' + j).prepend('<i class="fas fa-sun"></i>&emsp;');
                                                                        break;
                                                                    case '2':
                                                                        $('.in' + j).append(" / 구름조금");
                                                                        $('.in' + j).prepend('<i class="fas fa-cloud-sun"></i>&emsp;');
                                                                        break;
                                                                    case '3':
                                                                        $('.in' + j).append(" / 구름많음");
                                                                        $('.in' + j).prepend('<i class="fas fa-cloud"></i>&emsp;');
                                                                        break;
                                                                    case '4':
                                                                        $('.in' + j).append(" / 흐림");
                                                                        $('.in' + j).prepend( '<i class="fas fa-smog"></i>&emsp;');
                                                                        break;
                                                                    }
                                                                }//if 종료
                                                            }//success func 종료
                                                        });
                                            });
                        });
cs


길어보긴하지만 딱히,, 다 반복되는 형식이라 어렵진않다.


중간중간 주석처리를 보면 아시겠듯이, 윗부분부터 핵심부분을 살펴보면, 처음에 동네예보시간에 맞춰 시간을 설정해주는 부분이 있는데,

내가 사용한 api는 실시간 예보 수준은 아니고 3시간에 한번 갱신되는 형식이라 02시부터 23시까지 3시간 단위로 갱신된다.

그렇기 때문에 현재시간을 그대로 넣으면 오류가 나면서 나타나지 않기때문에 예보에 맞게 가까운 시간대의 예보를 나타나게 해준 것이다.


또한, 자동으로 위치값을 받아와서 나타내주는 형식이 아니기때문에 기상청에서 제공하는 측정위치좌표값을 배열에 저장해주었다.

제공되는 엑셀파일에는 세세한 동단위까지 좌표값이 있었던 걸로 기억하는데, 나는 각 지역의 제일 위에있던 좌표값을 넣어주었다.


그리고 나는 xml형식으로 진행하였다. 데이터를 받아오면, 카테고리에 지역의 정보를 알 수 있는 항목이 많은데

나는 대표적으로 기온과 하늘상태 강수형태를 받아왔다. 카테고리에서 저 값을 찾으면 그 안에 항목값을 받아오는 그런 형식.

하늘상태나 강수형태는 숫자로 값이 나타나게 되는데, 그 값을 적절하게 바꾸어주었다. 그리고 아이콘도 추가해줌!


썩~ 좋은 코드는 아닌것 같지만,, 일단은 사용에 의의를 둔,, 그런ㅎㅎㅎ


1
2
3
4
5
6
7
<div class="vis-weather">
                <h1>전국 날씨</h1>
                <ul class="list-group list-group-flush weather"
                    style="font-weight: 600;">
                    <!-- <li class="list-group-item weather"></li> -->
                </ul>
</div>
cs
ㅇㅇ

이 부분은 html부분이다. 혹시 참고하실 분 있으면 참고하시길바랍니당~^-^!

이상 기상청 오픈api를 활용하여 전국 날씨 띄우기 끝입니다!

Comments