Computer Science/FrontEnd

노마드 코더 JS | #8 Weather

토마토. 2022. 2. 25. 23:09

#8.0 Geolocation

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    alert("you live it" + lat+ lng);
}
function onGeoError(){
    alert("can't find you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

#8.1 Weather API

const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
const API_KEY = "c96cb91a075021b0247d52f6b2ea1e72";

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)=>{
            city.innerText = data.name;
            weather.innerText = `${data.weather[0].main}/${data.main.temp}`;
        });
    console.log("lat", lat);
    console.log("lon", lon);
    console.log("data", data);
}
function onGeoError(){
    alert("can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

#8.2 Conclusions