JavaScript

[Javascript]페이지 개발: API를 통한 날씨정보

vhxpffltm 2019. 12. 28. 17:19
반응형

이전까지 localstorage 사용과 배경화면을 처리하는 과정을 거쳤다.

 

마지막으로 날씨 정보를 불러와 웹 페이지에 표시해보도록 한다. 여기서는 데이터만 가져와 한번 만들어본다.

코드먼저 살펴보자

 

index.html

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
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
<title>123</title>
    <link rel = "stylesheet" href="index.css" >
</head>
<body>
    <div class="js-clock">
    <h1 class = "js-title">00:00</h1>
 
    </div>
    <form class="js-form form">
        <input type = 'text' placeholder="what is your name??"/>
    </form>
    <h4 class="js-greet greet"></h4>
 
    <form class="js-todoform">
        <input type="text" placeholder="Write a to do"/>
    </form>
    <ul class="js-todolist"> </ul> 
    <span class="js-wea"></span>
 
 
    <script src="clock.js"></script>
    <script src="hi.js"></script>
    <script src="todo.js"></script>
 
    <script src="background.js"></script>
    <script src="weather.js"></script> 
</body>
</html>
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

weather.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
const COORDS = 'coords'
const apikey = '~~~~~~~';
const wea = document.querySelector(".js-wea");
 
function getweather(lat,long){
    //데이터를 얻는 함수
    fetch(
    `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${apikey}&units=metric`
    ).then(function(res){//데이터가 우리한테 넘어왔을때, 즉 fetch가 완전히 완료된 후, js에서 뭔가를 끝날때까지 기다리도록 함
        return res.json();//json을 얻음
    }).then(function(json){
        console.log(json);
        const temp = json.main.temp;
        const place = json.name;
        wea.innerText = `${temp} @_@ ${place}`;
    });
    //데이터를 얻음, 홈페이지에서 확인 가능
    //데이터가 우리한테 완전히 넘어와서 한수를 호출할거
}
 
function savecoord(obj){
    localStorage.setItem(COORDS,JSON.stringify(obj));
    //저장값은 스트링이다.
}
 
function handelsucces(position){
    console.log("handle Geo Success!!");
    console.log(position.coords.latitude);
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    const coordsobj = {
        latitude,
        longitude
    };
    savecoord(coordsobj); //위치정보를 저장한다.
    getweather(latitude,longitude)
}
function handleerror(){
    console.log("handle Geo Error!!!");
}
 
function askcall(){
    navigator.geolocation.getCurrentPosition(handelsucces,handleerror);
    //현재위치를 가져오는 함수, 수락하지 않으면 에러, 수락하면 위치정보가 뜸
}
 
function loadcoords(){
    const loadCoords = localStorage.getItem(COORDS);
    if(loadCoords === null){
        askcall();
    }
    else{
        const parseCoords = JSON.parse(loadCoords);
        console.log(parseCoords);
        getweather(parseCoords.latitude,parseCoords.longitude);
        //좌표값을 가지고 있는경우 날씨를 얻는 함수를 바로 호출
    }
}
 
function init(){
    loadcoords();
}
 
init();
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

 

자바스크립트만 살펴볼텐데 내용이 좀 많다.  먼저 init 함수부터 보자.

 

loadcoords()

이 함수는 localstorage에서 아이템을 가져온다. 비어있다면 localstorage에 위치값을 넣을거고 그렇지 않으면 값을 날씨정보를 바로 표시할 것이다.

그래서 정보가 없으면 askcall()함수로 위치값을 가져온다 그 함수는 아래와 같다.

navigator.geolocation.getCurrentPosition(handelsucces,handleerror);

 

https://developer.mozilla.org/ko/docs/WebAPI/Using_geolocation에서 정보를 찾을 수 있다. 위의 코드로 현재 위치정보를 가져올 수 있다. 

 

웹 브라우저를 사용하면서 많이 보았을 것이다. 위의 함수로 현재 위치에 대한 권한에 허용을 하면 여러분의 localstorage에 정보가 저장되며 허용하지 않으면 저장되지 않는다. 확인은 개발자 도구를 통해 localstorage에서 확인하자.

 

 

허용을 눌러 현재 위치정보를 가지도록 하였다. 그렇다면 어떻게 가져오는 것일까 navigator를 보면 handlesucces()함수가 있다. 이 함수는 position을 인자로 받는다. 이 position을 보면 아래와 같다.

 

이 값을 토대로 우리는 position.coords.~~~ 으로 값들을 가져올 수있다. 즉 handlesucces()함수는 현재 위치의 위도와 경도값을 변수로 만들어 그것을 savecoords()함수로 localstorage에 저장하고 이후 getweather()함수로 날씨정보를 가져오게 된다. 위치 정보는 알았다, 그렇다면 날씨 정보는 어떻게 가져오는지 알아보자.

 

getweather()

날씨정보는 API를 사용하여 가져온다. openweathermap.org 이곳에서 무료로 사용가능하다.

 

이곳에서 API키를 복사하여 위의 코드처럼 사용한다. 키값은 중요하기에 현재는 가렸다. 

fetch는 네트워크 요청을 쉽게 해준다. 즉 API키를 이용해 얻은 정보들을 요청한다. 

 

위의 그림처럼 네트워크 텝을 통해 상태를 확인할 수 있다.

 

 

JSON으로 받아온 내용을 보면 위와 같은 main 내용을 볼 수 있다. 이를 통해 날씨정보에 대한 내용을 우리는 JSON으로 가지고 있다. 이 데이터를 우리는 HTML로 나타내면 되는것이다.

 

 

위와같은 결과를 얻을 수 있다. 부족한 내용은 코드의 주석을 활용하고 console.log를 통해 각 값들을 확인하며 이해해보자.

 

 

Reference

https://justmakeyourself.tistory.com/entry/fetch-api

https://developer.mozilla.org/ko/docs/WebAPI/Using_geolocation

https://openweathermap.org/current

 

반응형