동백 // 노마드 코더 바닐라JS: Weather

2021. 11. 12. 13:21강의 정리/노마드코더( 바닐라 JS 강의 )

반응형

출처 : https://nomadcoders.co/

 

Geolocation

 

핵심 : Geolocation를 위해 기본 환경을 세팅한다.

 

0. weather.js를 만들어주고, html에 import해준다.

 

 

1. weather JS에서 navigater 함수를 이용해서 사용자의 위치를 값으로 받는다.

tip // navigator 함수는 첫번 째 인자로 위치를 받는데 성공했을 때의 함수를 받고, 두번째 인자로는 에러가 발생했을 때 실행될 함수를 받는다.

 

// 위치를 받는데 성공했을 때의 함수
function onGeoOk(position) {
    // 위도 값을 저장함.
    const lat = position.coords.latitude;
    // 경도 값을 저장함.
    const lng = position.coords.longitude;
   
}

// 에러가 발생했을 때 실행될 함수
function onGeoError() {
    alert("Can't find you. No wather for you.");
}

// navigator 함수는 첫번 째 인자로 위치를 받는데 성공했을 때의 함수를 받고,
// 두번째 인자로는 에러가 발생했을 때 실행될 함수를 받는다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

 

 

 

2. https://openweathermap.org/ 에서 계정을 만들어줌.

 

 

 

 


 

 

Weather API

 

핵심 : Weather API를 적용시켜준다.

 

tip // API는 다른 서버와 이야기 할 수있는 방법이다.

 

 

 

0. https://openweathermap.org/current 에서 아래 api를 사용할거임.

 

0-1. 주소창에 우리가 전에 받았던 위도와 경도값과 api id을 위의 api call에 넣어서 주소창에 검색해줌.

tip// api id는 사이트 내 프로필에 있음.

그러면 위 같은 사진(아래 코드로 보기 쉽게 나열 했음.)의 결과값이 나옴.

{"coord":
	{"lon":126.8974,"lat":35.1207},
 "weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],
 "base":"stations",
 "main":{"temp":282.77,"feels_like":279.74,"temp_min":282.77,"temp_max":282.77,
 "pressure":1018,"humidity":65,"sea_level":1018,"grnd_level":1009},
 "visibility":10000,
 "wind":{"speed":6.52,"deg":300,"gust":10.52},
 "clouds":{"all":79},
 "dt":1636687801,
 "sys":{"type":1,"id":8075,"country":"KR","sunrise":1636668238,"sunset":1636705754},
 "timezone":32400,"id":1841811,"name":"seoul","cod":200}

 

 

1. JS에서 api call 즉 url을 부른다.

const API_KEY = "d72cc7077c109aca299bef3f2262643f";

// 위치를 받는데 성공했을 때의 함수
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`;
	// 실제로 url에 갈 필요 없이 JS가 대신 url을 부름.
    fetch(url);
}

 

 

tip // fetch는 개발자가 실제로 url에 갈 필요 없이 JS가 대신 url을 부름.

        fetch는 promise이다. 즉 당장에 뭔가 일어나는 것이 아닌 시간이 좀 걸린 뒤에 일어난다.

Json은 위의 문장 전부를 의미한다.

 

 

2. url에서 원하는 값(날씨)을 추출해야함.

1. 내가 있는 장소의 이름을 얻어야함.

2. 그 장소의 날씨를 얻어야 함.

 

 

fetch를 통해 반환 받은 객체가 response고, response 안의 문장의 전부를 json()이라고 한다.

 

 

const API_KEY = "d72cc7077c109aca299bef3f2262643f";

// 위치를 받는데 성공했을 때의 함수
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`;
    // 실제로 url에 갈 필요 없이 JS가 대신 url을 부름.
    fetch(url)
        
        // url을 불러오는 데 성공했다면(then) 반환받은 response를 받고, response의 json을 얻는다.
        .then(response => response.json())
        .then(data => {
            const name = data.name;
            const weather = data.weather[0].main;
        });

}

// 에러가 발생했을 때 실행될 함수
function onGeoError() {
    alert("Can't find you. No wather for you.");
}

// navigator 함수는 첫번 째 인자로 위치를 받는데 성공했을 때의 함수를 받고,
// 두번째 인자로는 에러가 발생했을 때 실행될 함수를 받는다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

 

3. index.html에서 태그를 만들어준다.

    <div id="weather">
        <span></span>
        <span></span>
    </div>

3-1. JS에서 위의 HTML element들을 연결해주고, innerText해준다.

// 위치를 받는데 성공했을 때의 함수
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`;
    // 실제로 url에 갈 필요 없이 JS가 대신 url을 부름.
    fetch(url)
        
        // url을 불러오는 데 성공했다면(then) 반환받은 response를 받고, response의 json을 얻는다.
        .then(response => response.json())
        .then(data => {
            // 각 변수에 HTML id와 element를 연결해주고, 그 안에 innerText 해줌.
            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;
        });

}

 

아래 코드를 추가해주면 온도도 나타낼 수 있다.

weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;

 

반응형