nodejs - fetch, 5일(120시간) 날씨 불러오기

_·2020년 5월 8일
0

nodejs code

목록 보기
7/10

// 참고 목록
https://openweathermap.org/city/1835848
https://wooooooak.github.io/javascript/2018/11/25/fetch&json()/
https://post-blog.tistory.com/15
https://developer.mozilla.org/ko/docs/Web/API/Geolocation/getCurrentPosition
//구글 크롬_Geolocation API
https://developer.mozilla.org/ko/docs/WebAPI/Using_geolocation

// 실패 목록
https://github.com/buche/leaflet-openweathermap


...
// 오류 코드
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`)
        .then(response => {
            let json = response.json();
            console.log(json);
            console.log(json.name);
            document.getElementById('text_area').value = json;
        });
...

오류 결과.
json.name 이 undefined 이다.


해결책 :

...
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`)
        .then(response => {
            return response.json();
        }).then(json => {
            console.log(json);
            console.log(json.name);
            document.getElementById('text_area').value = json;
        });
...

프로미스로 다음 then으로 넘겨야 한다.. 이유는 아직 모르겠다.


  1. fetch를 이용한 5일간 날씨 정보 얻어오기 완성 코드
<!--
* author : velog.io/@___
* path : ./index.html
-->
<!DOCTYPE html>
<html>
<head>
<title>5일간 (120시간) 날씨 불러오기</title>

<style>
    textarea{
        width: 300px;
        height: 300px;
    }
    input{
        width: 400px;
    }
</style>


<script src="./js/weather.js"></script>
</head>
<body>
<div class="main_container">
    <input id='text_area' value="5일 (120시간) 날씨 정보  (기본 : 서울)">
    <br />
    <textarea id='text_area0' ></textarea>
    <textarea id='text_area1'></textarea>
    <textarea id='text_area2'></textarea>
    <textarea id='text_area3'></textarea>
    <textarea id='text_area4'></textarea>
</div>
</body>
</html>
/*
* author : velog.io/@___
* path : ./js/weather.js
*/
const API_KEY = "a40a6bf35f38a0058b22a913a94f8577"

// 서울, 대한민국 위치. default
const COORD_LOC = {
    "latitude" : "37.58",
    "longitude" : "127",
};

if ('geolocation' in navigator) {
    /* 위치 정보 사용 가능. */
    alert('위치 정보 사용 가능');
    navigator.geolocation.getCurrentPosition(position => {
        COORD_LOC.latitude = position.coords.latitude;
        COORD_LOC.longitude = position.coords.longitude;
    })
} else {
    /* 위치 정보 사용 불가능 */
    alert('위치 정보 사용 불가능');
    // default : 서울, 대한민국 위치
    COORD_LOC.latitude = "37.58";
    COORD_LOC.longitude = "127";
}

function getWeather(latitude, longitude) {
    // today 날씨 정보
    //fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`)
    // 120 시간 날씨 정보, 3시간 단위 40개 get.
    fetch(`https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`)
        .then(response => {
            return response.json();
        }).then(json => {
            //console.log(json);
            //console.log(json.list);
            for (let index = -1; ++index < 40;) {
                document.getElementById(`text_area${Math.floor(index / 8)}`).innerHTML += `날짜:${json.list[index].dt_txt}, 기온:${json.list[index].main.temp} `;
                document.getElementById(`text_area${Math.floor(index / 8)}`).innerHTML += '\n';
            }
        });
}

function load() {
    getWeather(COORD_LOC.latitude, COORD_LOC.longitude);
}

load();

구글 크롬의 위치 확인 권한 요청이, html을 하드디스크에서 파일로 그냥 열고 끝내는 문제인지 허용을 하여도 크롬 설정에 적용이 안되는 듯 하다.


  1. 실행 결과


profile
_

0개의 댓글