[ JS : 실습 : Getting the Weather (3) ]

Teasan·2020년 12월 6일
0

JavaScript

목록 보기
10/15
post-thumbnail

📍 Javascript를 공부했을 때 학습노트에 정리해둔 것을 옮겨왔다.

우리가 원하는 json object를 가져오기 위해서는 .then 을 한번 더 사용해야한다.

function getWeather(lat, lon) {
    fatch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=units=metric`
    // json 데이터 가져오기 1
    ) .then(function (response) {
        return response.json();
    })
    // json 데이터 가져오기 2
    ) .then(function (json) {
        console.log(json);
    });
}

console.log(json); 실행결과

Step 4. JSON 데이터에서 가져온 결과를 웹페이지에 구현하기

  • html
<span class="js-weather"></span>
  • javascript
const weather = document.querySelector(".js-weather");
const API_KEY = "4842c80ba1638386637c9f75890d81a7";
const COORDS = 'coords’;

function getWeather(lat, lon) {
    fatch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=units=metric`
    ) // json 데이터 가져오기 1 
    .then(function (response) {
        return response.json();
    }) // json 데이터 가져오기 1
    .then(function (json) {
        const temperature = json.main.temp;
        const place = json.name;
        weather.innerText = `${temperature} @ ${place}`;
    });
    /* then()이 하는 역할은 기본적으로 함수를 호출하는 것이지만, fetch를 실행한 이후(API 데이터가 완전히 들어오고 난) 이후에 호출하는 것이다. */
}

function saveCoods(coordsObj){
    localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}

function handleGeoSucces(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    const coordsObj = {
        latitude,
        longitude
    };
    saveCoods(coordsObj);
    getWeather(latitude, longitude);
}

function handleGeoError(){
    console.log("can't accese geo location");
}

function askForCoords() {
navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError);
}

function loadCoords() {
    const loadedCoords = localStorage.getItem(COORDS);
    if (loadedCoords === null) {
        askForCoords();
    } else {
    const parseCoords = JSON.parse(loadedCoords);
    getWeather(parseCoords.latitude,    parseCoords.longitude)
    }
}

function init() {
    loadCoords();
}
init();

tip. 버튼 외곽선 없애주는 css 명령어

button {
    all: unset;
}
profile
일단 공부가 '적성'에 맞는 개발자. 근성있습니다.

0개의 댓글