자유게시판
기상청 날씨정보 api 활용 받아오기
별메아리
2023. 5. 26. 11:16
728x90
날씨 정보를 활용한 일기 예보 사이트를 만들어 볼려고 공공데이터 사이트에서 실시간 단기 예보 정보를 받아와서 웹페이지에 뿌려주는 코드를 작성해보았다.
Java Script로 기상청 api 활용하여 날씨 정보 받아오기
<!DOCTYPE html>
<html>
<head>
<title>Weather Information</title>
<script>
function getWeather() {
var xhr = new XMLHttpRequest();
var url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst'; /*URL*/
var queryParams = '?' + encodeURIComponent('serviceKey') + '='+'서비스키'; /*Service Key*/
queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1'); /**/
queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('1000'); /**/
queryParams += '&' + encodeURIComponent('dataType') + '=' + encodeURIComponent('JSON'); /**/
queryParams += '&' + encodeURIComponent('base_date') + '=' + encodeURIComponent('20230526'); /**/
queryParams += '&' + encodeURIComponent('base_time') + '=' + encodeURIComponent('0600'); /**/
queryParams += '&' + encodeURIComponent('nx') + '=' + encodeURIComponent('102'); /**/
queryParams += '&' + encodeURIComponent('ny') + '=' + encodeURIComponent('84'); /**/
xhr.open('GET', url + queryParams);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
var weatherText = document.getElementById('weather-text');
weatherText.textContent = response;
}
};
xhr.send('');
}
</script>
</head>
<body>
<h1>Weather Information</h1>
<button onclick="getWeather()">Get Weather</button>
<div id="weather-text"></div>
</body>
</html>
필요한 정보가 있다면 더 추가 하면 되는데 쿼리 파람에 추가하면 된다. 정보형식은 기상청 api 문서를 참조해야 한다.
다음 프로젝트에 짤막하게 날씨 정보라도 넣어 볼까 하여 일단 정리해서 올려놓았다.
혹시 제 티스토리를 보시는 분이 계신다면 요새 낮아진 설명 퀄리티에 죄송하단말을 드리겠습니다.
728x90