Frontend/JavaScript

바닐라 JS로 크롬 앱 만들기 ( #8 Weather)

:_: 2022. 4. 26. 18:19

 

 

Geolocation

weather.js를 만들고 

navigator.geolocation.getCurrentPosition 를 사용하면 내가 있는 곳의 위도와 경도를 알 수 있다.

날짜 정보는 https://openweathermap.org/api 에서 Current weather data 사용

 

Weather API

🎈 API

다른 서버와 이야기할 수 있는 방법

 

🎈 fetch

fetch 를 사용해서 실제로 URL에 갈 필요 없이 JS가 대신 URL 부른다.

fetch 은 당장 일어나지 않고 시간이 좀 걸린뒤 일어나므로 then 사용

 

weather.js

const API_KEY = "api key 값";

function onGeoOk(position){
    let lat = position.coords.latitude;   // 위도
    let lon = position.coords.longitude;  // 경도
    console.log("You live it", lat, lon);

    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;

    // fetch 은 당장 일어나지 않고 시간이 좀 걸린뒤 일어나므로 then 사용해야 한다.
    fetch(url)
        .then((response) => response.json())
        .then(data => {
           // console.log(data.weather[0].main);  // 날씨
            console.log(data)
            const weather = document.querySelector("#weather span:first-child");
            const city = document.querySelector("#weather span:last-child");
            
            // weather.innerText = data.weather[0].main;
            // data.main.temp 온도
            weather.innerText = `${data.weather[0].main} / ${data.main.temp}`; 
            city.innerText = data.name;
    });
}

function onGeoError() {
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)

 

index.html

<div id="weather">
    <span></span>
    <span></span>
</div>

 

 

 

😃 날씨 API 를 마지막으로 '바닐라 JS로 크롬 앱 만들기' 과정은 끝이 났다.

바닐라 JS 를 알게되서 너무 재미있었다.

이것저것 만들어 보면서 더 자세히 익혀봐야겠다.

 

😃 해당 소스

 

 

' 노마드 코드 - 바닐라 JS로 크롬 앱 만들기' 공부하면서 정리한 내용입니다.

 

728x90