본문 바로가기
IT 개발/JavaScript

도시하천) 강우 레이더 조회

by Love of fate 2020. 3. 17.
728x90
반응형

03.02 강우 레이더 조회 (한강 홍수통제소 레이더 영상 조회)

-- 한강홍수통제소 openAPI 사용

-- http://www.hrfco.go.kr/web/openapiPage/reference.do# 

 

1) 아래 xml에 Api key와 Url 생성

- system_config_properties_dev.xml

- system_config_properties_production.xml

- system_config_properties_staging.xml

 

* 참고 자료

-- %s 는 HRFCO_RADAR_KEY가 들어갈 자리

<entry key="HRFCO_RADAR_URL">http://api.hrfco.go.kr/%s/radar/list/COMP.json </entry>
<entry key="HRFCO_RADAR_KEY">52832662-D130-4239-9C5F-730AD3BE6BC6</entry>

system_config_properties_dev.xml
0.01MB


* sfc_rainfall.jsp

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link href="<c:url value='/resources/css/sfc_rainfall.css'/>" rel="stylesheet" type="text/css" >
<script type="text/javascript" src="<c:url value="/resources/js/index/sub/sub_common.js"/>" charset="utf-8"></script>
<script type="text/javascript">
    var currNavMenuGroup = "menu_sfc";
    var currNavMenuItem = "sfc_rainfall";
</script>
<div class="subContainer on">
    <div class="titleDiv">
        <div class="title">
            종관기상관측(기상청)
        </div>
        <div class="subTitle">
            강우 레이더 정보 조회
        </div>
        <div class="location">
            수문기상정보 > 종관기상관측(기상청) > 강우 레이더 정보 조회
        </div>
    </div>
    <div class="subLineDiv"></div>
    <div class="subContent">
        <div class="subContentSearhArea" style="position: sticky;">
            <div class="row" style="height: 97px;">
                <div class="btn">
                    <a href="#" class="prev_btn"><img src="/resources/images/icon/prev_btn.png" alt="이전" class="big"></a>
                    <a href="#" class="play_btn off"><img src="/resources/images/icon/play_btn.png" alt="재생" class="big"></a>
                    <a href="#" class="next_btn"><img src="/resources/images/icon/next_btn.png" alt="다음" class="big"></a>
                </div>
                <div class="subContentClickBox selectIcon">
                    <ul></ul>    
                </div>
            </div>
        </div>
        <div class="subContentArea">
            <div class="subContentGraph" style="height: 300px; display:none;">
                <div id="sfcHeavyRainChart" style="height: 300px;">
                </div>
            </div>
            <div class="subContentTable">
                <div class="subContentCurrInfoArea">
                    <div class="currDateDiv">
                        <span id="currDateInfo"></span>
                    </div>
                </div>
                <table class="listTable">
                    <thead id="sfcRainlessThead"></thead>
                    <tbody id="sfcRainlessTbody">
                        <tr>
                            <td>
                                <img src="">
                            </td>
                        </tr>                        
                    </tbody>
                </table>
                <div class="subFooter">
                    <a id="saveBtn" href="#">
                        <%-- <img src="<c:url value="/resources/images/new/excel_save.png"/>" style="float: right; cursor: pointer;"> --%>
                    </a>
                    <div id="paging" class="pageDiv"></div>
                </div>
            </div>
        </div>
    </div>
</div>
 

* sfc_rainfall.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
var yy = null;
var mm = null;
var dd = null;
var hh = null;
var hhmm = null;
var date = null;
 
var timer =  null;
 
jQuery(window).on('load'function() {
 
    makeRainFallInfo();
    
    //시간버튼 클릭 시 
    jQuery('.imgBtn').click(function(){
        var targetDate = jQuery('.subContentTable > .subContentCurrInfoArea > .currDateDiv > #currDateInfo');
        var boolean = jQuery(this).is('.on');
        
        if(!boolean){
            
            jQuery('.imgBtn').removeClass('on');
            jQuery(this).addClass('on');
            
            var imgUrl = jQuery(this).attr("src");
            var day = jQuery(this).attr("date");
            setDate(day);
 
            jQuery('#sfcRainlessTbody IMG').attr('src', imgUrl);
            targetDate.text(date);
        }
    });
    
    //다음 버튼 클릭 했을 시 
    jQuery('.next_btn').click(function(){
        var target = jQuery('.subContentClickBox.selectIcon LI A.on');
        jQuery(target).parent().next().find('A').trigger('click');
    });
    
    //이전 버튼 클릭 했을 시
    jQuery('.prev_btn').click(function(){
        var target = jQuery('.subContentClickBox.selectIcon LI A.on');
        jQuery(target).parent().prev().find('A').trigger('click');
    });
    
    //재생 버튼 클릭 했을 시 
    jQuery(".play_btn").click(function(){
        
        var boolean = jQuery('.play_btn').is('.on');
        if(boolean){
            clearInterval(timer);
            jQuery('.play_btn').removeClass('on').addClass('off');
            jQuery('.play_btn.off').find('img').attr('src''/resources/images/icon/play_btn.png');
        }else{
            var indexCp = jQuery('.subContentClickBox.selectIcon LI').length-1;
            jQuery('.play_btn').removeClass('off').addClass('on');
            jQuery('.play_btn.on').find('img').attr('src''/resources/images/icon/stop_btn.png');
 
            timer = setInterval(function (){
                
                var target = jQuery('.subContentClickBox.selectIcon LI A.on')
                var index = target.parent().index();
                
                if(index === indexCp){
                    clearInterval(timer);
                    jQuery('.play_btn').removeClass('on').addClass('off');
                    jQuery('.play_btn.off').find('img').attr('src''/resources/images/icon/play_btn.png');
                    
                    return;
                }
                jQuery(target).parent().next().find('A').trigger('click');
                
            }, 1500);
        }
    })
});
 
//강우 레이더 정보 조회 
function makeRainFallInfo(){
 
    //var url = "http://api.hrfco.go.kr/52832662-D130-4239-9C5F-730AD3BE6BC6/radar/list/COMP.json";
    ajax.call('agr_measure_info/menu_sfc/getHrfcoRadarInfo.do''POST'nullnullfalsefunction(data) {
                
        var d = data.DATA;
        var content = null;
        d = JSON.parse(d);
        
        content = d.content;
                
        if(content && content.length > 0 ){
            initRainFallInfo(content);
        }
    });
}
 
//강우 레이더 정보 조회 데이터 뿌리기
function initRainFallInfo(content){
    
    var targetTBodyImg = jQuery("#sfcRainlessTbody IMG");
    var target = jQuery(".subContentClickBox.selectIcon ul");
    var targetDate = jQuery('.subContentTable > .subContentCurrInfoArea > .currDateDiv > #currDateInfo');    
    
    for(var i =0; i < content.length; i++){
        
        var img = content[i].img; 
        var lastIdx = img.lastIndexOf("COMP");    
        var day = img.substring(lastIdx + 4, img.length - 4);
        
        setDate(day);
        
        var liTag = "<li><a href='#' class = 'imgBtn' src = " +  img + " date =" + day + ">" + hhmm + "</a></li>";
        target.append(liTag);
        
        if(i == content.length-1){
            var imgUrl = content[i].img;
            target.find("li").last().find("a").addClass('on');
            
            targetTBodyImg.attr("src",  imgUrl);
            targetDate.text(date);
        }else{
            
            
        }    
    }    
};
 
//날짜 셋팅 
function setDate(day){
    
    yy = day.substr(0,4);
    mm = day.substr(4,2);
    dd = day.substr(6,2);
    hhmm = day.substr(8,2+ ":" + day.substr(-2);
    date = yy + "-" + mm + "-" + dd + " " + hhmm;
}
 

* HrfcoRaderController.java

 
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
package com.enjoybt.mdriv.measure.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import com.enjoybt.framework.net.http.WebUtil;
import com.enjoybt.mdriv.common.ResultMap;
 
@Controller
@RestController
@RequestMapping(value = "agr_measure_info/menu_sfc/")
public class HrfcoRadarController {
    
    @Value("#{sysConfig['HRFCO_RADAR_URL']}")
    private String hrfcoRadarUrl;
    
    @Value("#{sysConfig['HRFCO_RADAR_KEY']}")
    private String hrfcoRadarKey;
    
    @RequestMapping(value="getHrfcoRadarInfo.do", method=RequestMethod.POST )
    public ResultMap getHrfcoRadarInfo() {
        ResultMap result = new ResultMap();
        
        try {
          
          String url = String.format(hrfcoRadarUrl, hrfcoRadarKey);  
          String data = WebUtil.getResponseText(url);
          
          result.put("DATA", data);
          result.setSuccess(); 
          
         } catch(Exception e) {
             result.setFailure(); 
        }
        
        return result;
    }
}
 

* WebUtil.java
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
    /**
     * Description : HTTP/HTTPS API 연계를 위한 기본 기능 메서드
     * @param reqUrl(String)                - 연결 URL
     * @param timeout(Integer)                - 연결 시간 정의(밀리세컨드)
     * @param method(String)                - HTTP Method 유형(ex : GET, POST)
     * @param encode(String)                - Connection 인코딩(ex : UTF-8)
     * @param headers(Map<String, String>)    - Connection연결시 보낼 Header 정보
     * @param param(Map<String, Object>)    - Connection연결시 보낼 파라미터 정보
     * @return (String)                        - 응답결과
     * @throws NoSuchAlgorithmException    
     * @throws KeyManagementException
     */
    public static String getResponseText(String reqUrl, Integer timeout, String method, String encode, Map<StringString> headers, Map<String, Object> param) throws NoSuchAlgorithmException, KeyManagementException {
        HttpURLConnection httpURLConnection = null;
        InputStream is = null
        String result = null;
        try {
            String query = null;
            if(param != null) {
                StringBuffer paramBuffer = new StringBuffer();
                Iterator<String> keys = param.keySet().iterator();
                while(keys.hasNext()){
                    String paramKey = keys.next();
                    Object val = param.get(paramKey);
                    paramBuffer.append(paramKey+"="+val+"&");
                }
                query = paramBuffer.toString();
                query = query.substring(0, query.lastIndexOf("&"));
            }
            if("POST".equals(method.toUpperCase())) {
                is = new ByteArrayInputStream(query.getBytes(encode));
            }else{
                if(query != null) {
                    if(reqUrl.indexOf("?"!= -1) {
                        reqUrl += query.toString();
                    }else{
                        reqUrl += ("?" +query.toString()); 
                    }
                }
            }
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
 
                public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                }
 
                public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                }
            } };
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            LOGGER.debug("Request URL : " + reqUrl);
            URL targetURL = new URL(reqUrl);
            httpURLConnection = (HttpURLConnection)targetURL.openConnection();
 
            if(timeout > 0) {
                httpURLConnection.setConnectTimeout(timeout);
                httpURLConnection.setReadTimeout(timeout);
            }
            
            if(headers != null && !headers.isEmpty()) {
                Iterator<String> iterHeaderKey = headers.keySet().iterator();
                
                while(iterHeaderKey.hasNext()) {
                    String key = iterHeaderKey.next();
                    httpURLConnection.addRequestProperty(key, headers.get(key));
                    LOGGER.debug("HEADER("+key+") : " + headers.get(key));
                }
            }
            httpURLConnection.setRequestMethod(method.toUpperCase());
            if("POST".equals(method.toUpperCase())) {
                httpURLConnection.setDoOutput(true); 
                IOUtils.copy(is, httpURLConnection.getOutputStream());
            }
            
            if(httpURLConnection.getResponseCode() == 200) {
                result = IOUtils.toString(httpURLConnection.getInputStream(), encode);
            }else{
                result = IOUtils.toString(httpURLConnection.getErrorStream(), encode);
            }
            
        } catch (IOException e) {
            LOGGER.error("Request Error", e);
        } finally {
            try { if(is != null) { is.close(); } } catch(IOException e) {
                LOGGER.error("exception", e);
            } 
            if(httpURLConnection != null) { httpURLConnection.disconnect(); }
        }
        
        return result;
    }
 

* 결과물


* 참고자료 

 

WebUtil.java
0.01MB
HrfcoRadarController.java
0.00MB

728x90
반응형