언어&프레임워크/JavaScript

Weather API로 날씨정보 가져오기(getCurrentPosition, fetch, 섭씨온도로 변환)(in JavaScript)(2)

밍풀 2022. 12. 27. 22:55

usr의 위치(geolacation)주는 함수를 사용해 날씨를 화면에 출력하기

 

usr의 위치(geolacation)주는 함수 ; navigator.geolacation.getCurrentPosition(onGeoOk,onGeoError );

브라우저에서 위치좌표를 주는 함수임 

getCurrentPosition 함수는 두개의 인자를 받음 ;  모든게 잘 됐을때 실행될 success함수, error났을때 실행될 함수 

 

success함수, 즉 위의 onGeoOk 함수는 geolocation object(위치정보 들어있는) 하나를 인자로 받게 됨

즉 function onGeoOk(position){ console.log(positon); }; 함수가 있을때 position자리에 얻은 위치정보 object가 들어감

 

출력해보면 아래와 같은식으로 위치정보가 들어간 객체가 출력됨을 확인 할 수 있음 

 

위도와 경도를 position.coords.latitude; 등과 같이 접근 할 수 있음을 알게됨

 

이제 위치의 숫자정보(위도, 경도)를 통해 위치장소와 현재날씨를 바꿀 수 있도록 아래 사이트를 이용함

https://openweathermap.org/

 

Weather API - OpenWeatherMap

Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.

openweathermap.org

 

api = 다른 서버와 이야기 할 수 있는 방법

API doc 에서 위치에 대한 현재 날씨 얻을 수 있음

api 문서 클릭시 위치에 대한 현 날씨 얻을 수 있음

위에서 {lat} , {lon} 에 위도경도 정보 입력, api key 는 my api key 에서 정보 가져오면 됨

(가입하고 메일확인한뒤 몇분 기다려 활성화됨)

대입한 url로 이동시 아래와 같은 정보를 얻을 수 있음 (크롬앱 스토어에서 JSON viewr 다운 받으면 아래와 같이 정돈되어 나옴)

 

JS 에서 URL 부르기 => fetch 함수 이용

자바스크립트에서 fetch(url) 실행시키면 아래와 같이 위치허용시 network 탭에 뭐가 뜸

url로 직접 갈 필요 없이 js가 대신 url불러주게됨 

그런데 온도가 화씨온도로 나옴, 섭씨온도로 바꾸기 위해 api wether map 에서 방법확인

 

url 뒤에 &units=metric 추가하면 json에 섭씨온도로 나옴

 

fetch 함수는 promise임 당장 뭔가 일어나지 않고 나중에 일어난단 뜻

서버에 뭐 물어봤는데 응답 5분걸리면 서버응답 기다려야해 이때 then사용

url fetch 하고 다음으로 reponse 받고 또 그걸통해 response의 json받아야함

그리고 또 거기서(json) 날씨정보, 장소이름 정보 얻음

 

예를 들어 위에서 name 의 도시명, 날씨 main 에 있는 정보 얻어 콘솔창에 출력하고싶을때 아래와 같이 작성 

fetch(url).then((response)=>response.json()).then((data)=>console.log(data.name, data.weather[0].main));

 

이제 본격적으로 웹화면에 날씨랑 도시 등 정보 보여주기 위한 작업 

html에 id weather인 태그 만들어주고 안에 날씨랑 도시이름 정보 붙이기 

1
2
3
4
5
6
7
8
9
    fetch(url)
    .then((response)=>response.json())
    .then((data)=>{
        const weather= document.querySelector("#weather span:first-child");
        const city=document.querySelector("#weather span:last-child");
        weather.innerText = data.weather[0].main;
        city.innerText=data.name;
        })
}
cs

 

wether.js 완성본

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const API_KEY = "";
 
function ok(position){
    const lat = position.coords.latitude;//console.log로 position의 object확인해 필요정보 위치 파악함
    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");
        weather.innerText = `${data.weather[0].main}/${data.main.temp}`;
        city.innerText=data.name;
        })
}
 
function error(){
    alert("I can't find you, no weather for you. ");
}
 
navigator.geolocation.getCurrentPosition(ok, error);//getCurrent함수가 위치정보찾기성공시ok, 실패시error함수 실행
 
 
 
cs

 

api 책으로만, 글로만 이해했었는데 실제로 조금이나마 사용해보니 이해가고 잼남 완강한 내자신 감사하다 ;)

그리고 얼른 git사용법 익혀야겠다..