[ JS : 실습 : Getting the Weather (2) ]

Teasan·2020년 12월 6일
0

JavaScript

목록 보기
9/15
post-thumbnail

📍 Javascript를 공부했을 때 학습노트에 정리해둔 것을 옮겨왔다.

API는 다른 서버로부터 손쉽게 데이터를 가져올 수 있는 수단이다.
https://home.openweathermap.org/ 를 이용하면 해당 웹사이트를 통해 원하는 종류의 데이터를 얻을 수가 있다.

✔️ 이번에 이용할 API 데이터 주소

api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={your api key}

API 데이터 주소를 수정하여 사용해야 한다.

/* openweathermap 사이트에서 긁어온 내 계정의 API KEY 주소를 변수로 설정한 것이다. */
const API_KEY = "4842c80ba1638386637c9f75890d81a7";

/* fetch( ) 함수를 사용하여 API 데이터 주소를 불러온다. */
fetch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`
)

Step 1. 외부에서 API 데이터 가져오기

/* openweathermap 사이트에서 긁어온 내 계정의 API KEY 주소를 변수로 설정한 것이다. */
const API_KEY = "4842c80ba1638386637c9f75890d81a7";
const COORDS = 'coords’;

/* 외부 API 데이터를 실행할 함수 */
function getWeather(lat, lon) {
    // API 데이터를 얻을 때 사용하는 fatch( ) 이용
    fatch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`
    )
}

function saveCoods(coordsObj){
    localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}

function handleGeoSucces(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    const coordsObj = {
        latitude,
        longitude
    };
    saveCoods(coordsObj);
    // 외부에서 API 데이터를 얻는 함수 실행
    getWeather(latitude, longitude);
}

function handleGeoError(){
    console.log("can't accese geo location");
}

function askForCoords() {
navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError);
}

function loadCoords() {
const loadedCoords = localStorage.getItem(COORDS);
    if(loadedCoords === null) {
        askForCoords();
    } else {
    // getWeather() 함수를 호출한다.
    const parseCoords = JSON.parse(loadedCoords);
    console.log(parseCoords);
    }
}

function init() {
    loadCoords();
}
init();

만약 local storage에 아무것도 없으면 getWeather( )가 호출된다. local storage에 아무것도 업으면 askForCoords( )가 실행되고 askForCoords( )(좌표를 요청하는 함수)에서 정상적으로 위치정보를 가져오게 되면 handleGeoSucces( )(좌표 요청이 허락된 함수)가 실행되는데, handleGeoSucces( )안에서 API가 최종적으로 호출되기 때문이다.

console.log(parseCoords); 실행화면

Step 2. 외부에서 API 데이터 가져오는 함수(위도, 경도) 최종 호출하기

function loadCoords() {
const loadedCoords = localStorage.getItem(COORDS);
    if(loadedCoords === null) {
        askForCoords();
    } else {
    // getWeather() 함수를 호출하기 위한 변수 선언
    const parseCoords = JSON.parse(loadedCoords);
    // getWeather( ) 함수 최종 호출하기
    getWeather(parseCoords.latitude,    parseCoords.longitude)
    }
}

검사 > Network > Request URL 의 주소를 복사해서 웹페이지에 로딩해보면

Request URL: https://api.openweathermap.org/data/2.5/weather?lat=37.623507200000006&lon=126.9152202&appid=4842c80ba1638386637c9f75890d81a7

실행결과해당 API 데이터의 내용을 볼 수 있다.

Tip. 해당 API 데이터의 결과 값을 metric(미터법)으로 보고 싶다면
Units format 페이지에서 해당 미터법을 이용할 수 있는 부분을 긁어와 기존의 API 주소에 복사 붙여넣기를 한다.

fetch (
  `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=units=metric`
)

Step 3. 외부에서 가져온 API 데이터에 따른 정보를 찾기

const API_KEY = "4842c80ba1638386637c9f75890d81a7";
const COORDS = 'coords’;

/* 외부 API 데이터를 실행할 함수 */
function getWeather(lat, lon) {
    fatch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=units=metric`
    )
    .then(function (response) {
        console.log(response);}
    ) 
    /* then()이 하는 역할은 기본적으로 함수를 호출하는 것이지만, fetch를 실행한 이후(API 데이터가 완전히 들어오고 난) 이후에 호출하는 것이다. */
}

console.log(response); 실행결과 response 에는 netWork 정보만 보이는 것을 확인할 수 있다.

profile
일단 공부가 '적성'에 맞는 개발자. 근성있습니다.

0개의 댓글