반응형
첫번째 테스트 앱으로, 흔한 날씨 어플을 만들어보기로 했습니다.
일단 얻을 수 있는 정보를 찾기위해 OpenAPI 를 찾아보니, 기상청에서 주는 정보가 있네요.
동네예보 조회 서비스입니다.
문서를 좀 읽어보니, 지역별 x, y 좌표를 넣으면 소소한(?) 날씨 정보를 주는 API 네요.
구글구글링을 해서, fetch를 이용해, JSON 데이터를 가져오고 해당 데이터를 이용할 수 있다는것을 알 수 있습니다.
활용할 수 있도록, 유틸을 만듭니다.
const DATA_API_KEY = "api키!"
const API_STEM = "http://apis.data.go.kr/1360000/VilageFcstInfoService/getUltraSrtFcst"
function xyUrl(x,y){
//30분전 의 정보를 가져온다 ( 실시간 정보는 업뎃이 안되서 안나옴 )
std_time = new Date()
std_time.setMinutes(std_time.getMinutes() - 30 )
today = getFormatDate(std_time)
time = getFormatTime(std_time)
return `${API_STEM}?serviceKey=${DATA_API_KEY}&dataType=JSON&numOfRows=1000&pageNo=1&base_date=${today}&base_time=${time}&nx=${x}&ny=${y}`
}
function fetchForeCast(x,y){
return fetch(xyUrl(x,y))
.then(resonse => resonse.json())
.then(responseJSON => {
/*
console.log(responseJSON.response.body.items.item[0].baseDate)
console.log(Object.keys(responseJSON.response.body.items.item).length)
console.log(responseJSON.response.body.items.item.filter((object) => {
return object['category'] === 'T1H' //기온
})[0].fcstValue)
console.log(responseJSON.response.body.items.item.filter((object) => {
return object['category'] === 'SKY' //하늘상태 0-5 맑음 6-8 구름많음 9-10 흐림
})[0].fcstValue)
console.log(responseJSON.response.body.items.item.filter((object) => {
return object['category'] === 'REH' //습도
})[0].fcstValue)
*/
return {
cloudy: responseJSON.response.body.items.item.filter((object) => { return object['category'] === 'SKY' })[0].fcstValue,
humidity: responseJSON.response.body.items.item.filter((object) => { return object['category'] === 'REH' })[0].fcstValue,
temperature: responseJSON.response.body.items.item.filter((object) => { return object['category'] === 'T1H' })[0].fcstValue
}
})
.catch(error => {
console.error(error)
})
}
function getFormatDate(date){
let year = date.getFullYear(); //yyyy
let month = (1 + date.getMonth()); //M
month = month >= 10 ? month : '0' + month; //month 두자리로 저장
let day = date.getDate(); //d
day = day >= 10 ? day : '0' + day; //day 두자리로 저장
return year + '' + month + '' + day; //'-' 추가하여 yyyy-mm-dd 형태 생성 가능
}
function getFormatTime(date){
let hour = date.getHours()
let minutes = date.getMinutes()
hour = hour >= 10 ? hour : '0' + hour
minutes = minutes >= 10 ? minutes : '0' + minutes
return hour + '' + minutes
}
export default { fetchForeCast: fetchForeCast }
간단하게 입력으로 격자x, 격자y 를 받아서, 온도, 습도, 구름량 을 표시하는 앱을 만들었습니다.
메뉴얼에 나와있는 것처럼 구름 1이면 맑음이네요..
다음시간에는 이미지좀 넣고, 좀더 이쁘게 바꿔보겠습니다.
반응형