clear_uncertainty

자바스크립트 입문[Javascript] - 자바스크립트로 날씨 기능 구현하기 본문

언어/자바스크립트(Javascript)

자바스크립트 입문[Javascript] - 자바스크립트로 날씨 기능 구현하기

SOidentitiy 2021. 8. 1. 20:32
728x90

2021-08-01

자바스크립트 학습일지입니다.

해당 내용은 노마드코더님의 <바닐라JS로 크롬 앱 만들기> 강의를 들으며 추가적인 학습을 정리한 내용입니다.


 

 

이번 포스팅에선 날씨기능을 구현해봅시다.

먼저, weather.js 라는 자바스크립트 파일을 생성한 뒤 HTML에 import 해줍시다.

 

위치를 알아야 , 그 위치의 날씨를 알 수 있기때문에 가장 먼저 구현할 것은, 사용자의 위치를 파악할 것입니다. 

위치를 파악하기 위해

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoEroor);

을 알아봅시다.

 

Navigator

Navigator 인터페이스는 사용자 에이전트의 상태와 신원 정보를 나타냅내며, 스크립트로 해당 정보를 질의할 때와 애플리케이션을 특정 활동에 등록할 때 사용합니다.

  •   Navigator.connection  - Read only 
    장치의 네트워크 연결 정보를 담은 NetworkInformation 객체를 반환합니다.
  •   Navigator.cookieEnabled (en-US) - Read only
    쿠키 (en-US) 설정을 할 수 있으면 참, 아니면 거짓을 반환합니다.
  •   Navigator.geolocation -  Read only
    장치의 위치 정보에 접근할 수 있는 Geolocation 객체를 반환합니다.

이 중 우리는 geolocation을 이용합시다.

 

Navigator.geolocation

웹에서 장치의 위치를 알아낼 때 사용할 수 있는 Geolocation 객체를 반환합니다.

보안 상의 문제로, 웹 페이지가 위치 정보에 접근을 시도하면 사용자에게 알림을 보내고 권한을 허용할지 묻습니다

 

Geolocation.getCurrentPosition()

Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.

구문 > navigator.geolocation.getCurrentPosition( succesfunction ,  errorfunction )

위와 같은 코드를 입력하면 먼저 보안상의 문제로 권한을 허용할 지 묻습니다.

그와 동시에 alert 알림창을 통해 ("Can't find you. No weather for you")가 나타납니다.

 

이를 허락하면 콘솔창에는 geolocation.geoCurrentPosition 메서드의

onGeoOk 함수가 작용해 position 정보가 나타납니다.

이 정보 중 필요한 것은 latitude(위도) 와 longitude(경도) 입니다. 이 두 값은 coords 에 저장됐으므로

function onGeoOk(position){
	const lat = position.coords.latitude;
	const lng = position.coords.longitude;
	console.log("You live in " , lat , lng);
}
function onGeoEroor(){
	alert("Can't find you. No weather for you")
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoEroor);

변수 lat과 변수 lng를 정의해줘 console창에서 결과를 확인해봅시다.

 

이제 이 위도와 경도를 지역/장소로 바꿔봅시다.

 

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

위 사이트를 회원가입해주고, API 메뉴에 들어간 뒤, 위치의 날씨를 알려주는  Current Weather Data 를 사용합시다.

 

사이트의 가이드대로 코드를 입력하면,

 

const API_KEY = ("51a56ffebfb070e2d3d4ec467bbfd36b");

function onGeoOk(position){
	const lat = position.coords.latitude;
	const lng = position.coords.longitude;
	const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`}

위와 같습니다.

url에 설정한 lat과 lng 을 적용하고, openweathermap의 고유 API 키를 사용해 url을 생성해줍시다.

 

설정된 URL은 디바이스가 접속한 지역에 따라 위와같은 정보를 제공합니다.

위의 정보를 활용해 디바이스가 접속한 지역의 날씨, 지역이름을 브라우저에 보이게 하기위해선, fetch( ) 를 이해해야합니다.

 

Fetch ( ) 

백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받습니다. 이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios 라이브러리를 사용할 수 있습니다. 참고로 Web API는 클라이언트 측에서 사용할 수 있는 자바스크립트 내장함수라고 생각하시면 됩니다.

 

fetch() 함수 기본형태

fetch('api 주소')
  .then(res => res.json())
  .then(res => {
    // data를 응답 받은 후의 로직
  });

fetch API의 기본형태는 위와같습니다. 

위의 기본형태는 아래 코드를 줄인 것입니다.  아래 코드를 이해하고 위의 코드를 활용합시다.

fetch('api 주소')
  .then(function(res) {
    return res.json();
  })
  .then(function(res) {
    // data를 응답 받은 후의 로직
  });

 

첫 번째 코드에서 res를 보며 드는 생각은 무엇이었나요? 3개의 res가 모두 똑같은 변수라고 생각했으면 변수의 scope(스코프) 부터 다시 공부하고 와야 합니다. 위 코드에서 변수의 scope는 각 함수이므로 첫 번째 then와 두 번째 then 안에 있는 res는 서로 다른 것입니다.

 

fetch() 함수 - res.json()의 의미

fetch('https://api.google.com/user', {
    method: 'post',
    body: JSON.stringify({
        name: "yeri",
        batch: 1
    })
  })
  .then(res => res.json())   // 왜 then이 두개고 res.json() 은 뭔지?
  .then(res => {
    if (res.success) {
        alert("저장 완료");
    }
  })

첫 번째 then의 res가 어떤 값이 들어오길래 res.json()을 리턴하는가? console.log를 찍어 확인해봅시다.

fetch('https://api.google.com/user', {
    method: 'post',
    body: JSON.stringify({
        name: "yeri",
        batch: 1
    })
  })
  .then(res => {       // 첫 번째 then
    console.log(res);  // 어떤 값이 나오는지 확인해보세요. 실제 잘 작동하는 api 주소가 필요합니다.

    return res.json();
  })
  .then(res => {       // 두 번째 then
    if (res.success) {
        alert("저장 완료");
    }
  })

첫 번째 then 함수에 전달된 인자 res는 http 통신 요청과 응답에서 응답의 정보를 담고 있는 객체입니다. Response Object 라고 합니다.

그런데 console을 확인해보시면 백앤드에서 넘겨주는 응답 body, 즉 실제 데이터는 보이지 않을 것입니다. 즉 { success: true } 라는 JSON 데이터는 위의 코드로는 console에 찍히지 않을 것이라는 말입니다.

응답으로 받는 JSON 데이터를 사용하기 위해서는 Response Object 의 json 함수를 호출하고, return 해야합니다. 그러면 두 번째 then 함수에서 응답 body의 데이터를 받을 수 있습니다.

 

 

다시 날씨기능 구현하기로 돌아와 코드를 작성해봅시다.

const API_KEY = ("51a56ffebfb070e2d3d4ec467bbfd36b");

function onGeoOk(position){
	const lat = position.coords.latitude;
	const lng = position.coords.longitude;
	const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
	fetch(url).then(response=> response.json())
		.then(data=> {
		const city = data.name;
		const weather = data.weather[0].main;
        console.log( city, weather)
	});
}

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

 navigator.geolocation.getCurrentPosition( onGeoOk ,  onGeoErr );

city와 weather을 설정해줍시다. 참고로 weather은 array 형식이므로 [0]을 기입하고,

원하는 정보인, 날씨는 weather 안의 main에 저장되있기때문에 data.weather[0].main을 weather로 설정해줍니다.

이를 console.log( city, weather) 을 통해 console 창에 띄우면 아래와 같이 잘 작동하는 것을 확인할 수 있습니다.

 

 

이제 console창이 아닌 브라우저에 작동하도록 HTML에 id값이 weather인 div와 그 자식으로 두개의 span을 넣어줍시다.

이를 브라우저에 나타나도록 하는 방법은 전 포스팅에서 많이 했으므로 설명을 생략하겠습니다.

 

최종 코드는 아래와 같습니다.

const API_KEY = ("51a56ffebfb070e2d3d4ec467bbfd36b");

function onGeoOk(position){
	const lat = position.coords.latitude;
	const lng = position.coords.longitude;
	const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
	fetch(url).then(response=> response.json())
		.then(data=> {
		const city = document.querySelector("#weather span:first-child");
		const weather = document.querySelector("#weather span:last-child");
		city.innerText = data.name;
		weather.innerText = data.weather[0].main;
	});
}

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

 navigator.geolocation.getCurrentPosition( onGeoOk ,  onGeoErr );

 

최종 브라우저는 아래와 같습니다.

 

 

이것으로, 노마드코더님의 강의 <바닐라 JS로 크롬 앱 만들기>가 끝났습니다.

처음 배우는 자바스크립트이지만, 친절한 강의와 직관적인 과제를 통해 한결 배우기 좋았던 것 같습니다.

이제 이 사이트를 HTML과 CSS를 통해 보기 좋은 사이트로 만들고, JS를 통해 새로운 기능을 넣어 포스팅하겠습니다.

 

 

노마드 코더 Nomad Coders

코딩은 진짜를 만들어보는거야!. 실제 구현되어 있는 서비스를 한땀 한땀 따라 만들면서 코딩을 배우세요!

nomadcoders.co

 

Thank you Nomadcoder!


 

출처

 

Navigator - Web API | MDN

Navigator 인터페이스는 사용자 에이전트의 상태와 신원 정보를 나타냅내며, 스크립트로 해당 정보를 질의할 때와 애플리케이션을 특정 활동에 등록할 때 사용합니다.

developer.mozilla.org

 

 

Navigator.geolocation - Web API | MDN

Navigator.geolocation 읽기 전용 속성은 웹에서 장치의 위치를 알아낼 때 사용할 수 있는 Geolocation 객체를 반환합니다. 웹 사이트나 웹 앱은 위치정보를 사용해 결과 화면을 맞춤 설정할 수 있습니다.

developer.mozilla.org

 

 

Geolocation.getCurrentPosition() - Web API | MDN

Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.

developer.mozilla.org

 

 

 

fetch() 함수 사용법 - Blog by Yeri

백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받습니다. 이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios 라이브러리를 사용할 수 있습니다. 참고로 Web API는 클라이언트

yeri-kim.github.io

 

 

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB As of Dec 2020, serving ~1.8 billion requests each month.

jsonplaceholder.typicode.com

 

 

 

노마드 코더 Nomad Coders

코딩은 진짜를 만들어보는거야!. 실제 구현되어 있는 서비스를 한땀 한땀 따라 만들면서 코딩을 배우세요!

nomadcoders.co

 

728x90