자바스크립트 - 날씨 정보를 불러오기.

Jin Yun·2023년 9월 18일
0

중요 키워드

fetch()

 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}`;
    });

fetch 함수는 쉽게 말하면 외부 데이터를 가져오게 도와준다. 자세히 풀면 HTTP response 객체를 래핑한 Promise 객체를 반환한다. 따라서 프로미스의 후속 처리 메서드인 then을 사용하여 resolve한 객체를 전달받을 수 있다.

위에 예제에서는 날씨 관련 사이트에서 API값을 입력한 http 주소를 요청하여 JSON파일 형태로 가져왔다.
가져온 데이터를 html에 있던 각각의 span에 대입하였다.


navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

Geolocation API는 사용자의 현재 위치를 가져오는 API로, 지도에 사용자 위치를 표시하는 등 다양한 용도로 사용할 수 있습니다. 이 글에서는 Geolocation API의 기초 사용법을 설명합니다. getCurrentPosition에서는 성공할경우와 실패할경우의 함수를 각각 만들어준다.

날씨정보 가져오기


const API_KEY = ? 

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}`;
    });
}

function onGeoError() {
alert("No weather.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

  1. navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)를 사용하여
  2. 실패할경우와 성공할경우 함수를 만든다.
  3. 위도와 경도를 변수에 저장하고 openweathermap url도 변수로 저장한다.
  4. fetch 함수를 사용하여 데이터를 요청한다.
  5. html에서 불러온 변수에 weather, city 요청한 데이터를 innerText 대입한다.
profile
호주 개발자

0개의 댓글

관련 채용 정보