Javascript

[노마드코더] 바닐라JS 공부 8일차 (Weather)

래모 2022. 1. 17. 00:07

유저의 위치 찾기

// Geolocation 8.0

navigator 객체

: 브라우저와 관련된 정보를 컨트롤함, 브라우저에 대한 버전, 정보 종류 등 관련된 정보 제공

function onGeoOk(position) {
    const lat = position.coords.latitude; // 위도 얻기
    const lng = position.coords.longitude; // 경도 얻기
    console.log("You live in", lat, lng);
}

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

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
// 사용자의 위치를 얻기 성공하면 전자를 실패하면 후자의 함수 실행

 

위치에 해당하는 날씨 정보 제공

// Geolocation 8.0

✔ weather API 사용

  1. https://openweathermap.org/ 로그인 or 회원가입
  2. API 탭에서 Current Weather Data api doc 클릭
  3. api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key} <- 이거 복사 후 위도, 경도, apikey 활용해서 사용 (화씨온도를 섭씨온도로 바꾸고 싶으면 뒤에 &units=metric 작성)

 

fetch()함수로 원격 API 호출

fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환

반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));

 

Promise 객체란?

https://programmingsummaries.tistory.com/325 링크 참고 (솔직히 뭔 소린지 잘 모르겠음..)

 

암튼 날씨도 완성!

결과

const API_KEY = "9785dfe45ad749fc5ec1d09983fee741";

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 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)