본문 바로가기
Study/Vanila JS

[노마드코더] 바닐라 JS로 크롬 앱 만들기 - 현재 날씨 알려주기

by 22정민 2022. 12. 22.

https://nomadcoders.co/javascript-for-beginners

 

바닐라 JS로 크롬 앱 만들기 – 노마드 코더 Nomad Coders

Javascript for Beginners

nomadcoders.co

<!--index.html-->

<!--생략-->
		<div id="weather">
            <span></span>
            <span></span>
        </div>
<!--생략-->
//weather.js

const API_KEY = "자기 api키 넣기";

function onGeoOK(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
    //javascript가 url을 호출하고 response를 받음 + response의 json을 얻음
    //내용을 추출했으면 data를 얻음
    fetch(url)
        .then(response => response.json())
        .then(data => {
            const weather = document.querySelector("#weather span:first-child");
            const city = document.querySelector("#weather span:last-child");
            city.innerText =  data.name;
            weather.innerText = `${data.weather[0].main} / ${data.main.temp}ºC`;
    });
}

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

navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);