๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript/Vanilla JS

[๋ฐ”๋‹๋ผJS๋กœ ํฌ๋กฌ ์•ฑ ๋งŒ๋“ค๊ธฐ] Getting the Weather part Two API

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 3. 3.
๋ฐ˜์‘ํ˜•

[์ถœ์ฒ˜-์œ ํŠœ๋ธŒ ๋…ธ๋งˆ๋“œ ์ฝ”๋” Nomad Coders]

https://youtu.be/l6hSze8vgVo

 

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Something</title>
    <link rel="stylesheet" href="index.css" />
</head>
<body>
    <div class="js-clock">
        <h1>00:00</h1>
    </div>
    <form class="js-form form">
        <input type="text" placeholder="What is your name?" />
    </form>
    <h4 class="js-greetings greetings"></h4>
    <form class="js-toDoForm">
        <input type="text" placeholder="Write a to do" />
    </form>
    <ul class="js-toDoList">
    </ul>
    <span class="js-weather"></span>
    <script src="clock.js"></script>
    <script src="greeting.js"></script>
    <script src="todo.js"></script>
    <script src="bg.js"></script>
    <script src="weather.js"></script>
</body>
</html>

 

 

weather.js

const weather = document.querySelector(".js-weather");

const API_KEY = "f97c1ed1e4b50ed233ccabf8c1ea2011";
const COORDS = 'coords';

function getWeather(lat, lng){
    fetch(
        `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
    ).then(function(response){
        return response.json();
    }).then(function(json){
        const temperature = json.main.temp;
        const place = json.name;
        weather.innerTest = `${temperature} @ ${place}`;
    });
}

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

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

function handleGeoError(){
    console.log("Cant access geo location");
}

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

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

function init(){
    loadCoords();
}

init();

 

๋ณด์•ˆ ๋ฌธ์ œ๋กœ ์œ„์น˜ ์„ค์ •์„ ํ•˜์ง€ ๋ชปํ•จ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€