본문 바로가기

자바스크립트 기기기초

#8.1 Weather API

  • fetch는 promise -> 반응이 일어나는 데 시간이 걸림
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>Hello from HTML!</title>
</head>

<body>
    <form id="login-form" class="hidden">
        <input required maxlength="15" type="text" placeholder="What is your name?" />
        <button>Log In</button>
    </form>
    <h2 id="clock">00:00:00</h2>
    <h1 id="greeting" class="hidden"></h1>
    <form id="todo-form">
        <input type="text" placeholder="Write a To Do and Press Enter" required/>
    </form>
    <ul id="todo-list"></ul>
    <div id="quote">
        <span></span>
        <span></span>
    </div>
    <div id="weather">
        <span></span>
        <span></span>
    </div>
    <script src="js/clock.js"></script>
    <script src="js/greetings.js"></script>
    <script src="js/quotes.js"></script>
    <script src="js/background.js"></script>
    <script src="js/todo.js"></script>
    <script src="js/weather.js"></script>
</body>

</html>
const API_KEY = "a6f2559162df44deffc73c104257b1ad";

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`;
    fetch(url).then(response => response.json())
    .then(data => {
        const weatherContainer = document.querySelector("#weather span:first-child");
        const city = document.querySelector("#weather span:last-child");
        city.innerText = data.name;
        weatherContainer.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    });
}

function onGeoError() {
    alert("널 못찾았다..날씨 못줘");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

'자바스크립트 기기기초' 카테고리의 다른 글

#8.0 Geolocation  (0) 2023.02.15
#7.8 Deleting To Dos part Three  (0) 2023.02.15
#7.7 Deleting To Dos part Two  (0) 2023.02.15
#7.6 Deleting To Dos part One  (0) 2023.02.15
#7.5 Loading To Dos part Two  (0) 2023.02.15