
이번에는 사용자의 위치 정보를 가져와 날씨를 확인하는 기능을 구현해보자.
학습 날짜 : 23.08.13
사용자의 위치(geolocation)를 알려주는 함수에 대해 알아보자.
navigator.geolocation.getCurrentPosition();
getCurrentPosition은 2개의 argument가 필요하다.navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);onGeoOk()onGeoError() 를 입력한다.position.coords.latitude, 경도 position.coords.longitude학습 날짜 : 23.08.13
Weather API(https://openweathermap.org/)
Current Weather Data API를 활용하여 해당 위치의 날씨를 확인해보자.

위도, 경도, 발급받은 API key를 넣어주면 날씨 정보를 얻을 수 있다.
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`;
fetch(url);
이제 위치 이름(name)과 날씨(weather)를 얻어보자.

url에 unit을 같이 보낼 수 있다. url 뒤에 units=metric을 추가해준다.
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 name = data.name;
        const weather = data.weather[0].main;
    });
}
이제 이름과 날씨를 얻었으니 HTML에 표시해보자.
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 weater = document.querySelector("#weather span:first-child");
        const city = document.querySelector("#weather span:last-child");
        city.innerText = data.name;
        weater.innerText = `${data.weather[0].main} / ${data.main.temp}도`;
    });
}