본문 바로가기

TIL LIST/JavaScript

[chrome app 코딩 챌린지] 5. 위치 정보 가져오기(API)

API는 직접 구현하기 힘든 서비스를 구현할 수 있게 해주는 프로그래밍 인터페이스다. 홈페이지에 카카오맵 또는 구글맵을 넣어 실시간 위치를 보여줄 수 있고, 카카오톡 API를 통해 메세지를 보낼 수도, 페이스북이나 인스타그램 API를 통해 게시글을 공유할 수도 있다. 위치, 소셜 뿐만 아니라 API는 다양한 방면에서 쓰이고 있다. 

mdn Web API 모음: https://developer.mozilla.org/ko/docs/Web/API

여기에서는 위치 API인 Geolocation API로 사용자의 위치 정보를 받아오고, 그 좌표를 open Weather API 에 입력해 현재 날씨 데이터를 실시간으로 업데이트 해준다.

코드 리뷰

function onGeoSuccess(position) {
    const lat = position.coords.latitude; // 위도
    const lon = position.coords.longitude; // 경도
}

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

navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);

먼저 Geolocation API를 JavaScript에 입력해야 하는데 navigator.geolocation 객체를 통해 사용 할 수 있다.
navigator.geolocation 객체는 웹에서 사용자의 위치를 알아낼 때 사용할 수 있는 Geolacation 객체를 반환한다. 그리고 현재 위치를 가져오기 위해 Geolocation.getCurrentPosition() 메서드를 호출하면 사용자의 현재 위치를 조사한 후 GeolocationPosition 객체로 반환한다. 위치를 알아낸 후엔 지정된 콜백 함수(괄호) 를 호출한다. 이 과정중 오류가 발생할 때 호출할 오류 콜백은 두번째 매개변수로 지정한다.

 

그래서 위 코드에선 성공할 때 실행하는 함수는 onGeoSuccess, 실패할 때 실행하는 함수는 onGeoError로 처리했다. 만약 정보를 가져오는데 성공한다면 onGeoSuccess를 실행할 것이고, 실패한다면 onGeoError 함수를 실행할 것이다.

위 권한 요청 창에서 '차단'을 누르면 onGeoError가 실행되고 Geolocation API 를 사용할 수 없다.

 

GeolocationPositon 객체에는 여러 값이 있는데 우리가 필요한 것은 사용자의 위치 좌표다.

 

Geolacation API 객체를 반환해 Geolocation.getCurrentPosition() 메서드를 호출했다. 그리고 그 메서드는 GeolocationPosition 객체로 반환한다고 위에서 설명했다. 그 Position을 onGeoSuccess에 인자로 넣어준다. 그리고 그 인자를 콘솔 로깅하면 GeolocationPosition 객체가 출력된다.

 

그 객체안에 위치 좌표값이 들어있는데 그것을 각각 lat과 lon에 할당해준다.

 

그리고 우리는 이제 Weather API를 호출해줘야 한다. 홈페이지에 접속해보면 API 호출하는 방법을 설명해 두었다. 아래의 url 주소에 좌표값과 API key를 넣고 웹에 접속하면 JSON 파일로 해당 위치의 현재 날씨 데이터를 호출할 수 있다. 

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
<div class="weather__info window-cont">
    <img src="images/info.png" alt="">
    <div><h1></h1><span></span></div>
</div>
const API_KEY = "홈페이지 가입을 통해 개인 API key를 얻을 수 있다"

function onGeoSuccess(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__info h1")
            const city = document.querySelector(".weather__info span")
            weather.innerText = `${data.weather[0].main}, ${Math.ceil(data.main.temp)}℃`;
            city.innerText = data.name;
        });
    // promise 약속 ==> 당장 일어나지 않고 시간이 좀 흐른 뒤에 일어남
    // Promise.prototype.then()
}

휴, 여기까지 이해하는 데 한참 걸렸다. 하지만 산넘어 산이라고 fetch와 .then이라는 새로운 개념은 또 뭘까? 이 내용은 아래의 링크에서 추가적으로 공부했다.

https://velog.io/@sham/Fetch%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80

구글 검색으로 찾은 sham님의 벨로그를 정독하며 그나마 이해할 수 있었다. 너무 너무 감사합니다.

이 외에

API 페이지를 보다가 HTML Drag and Drop API 를 봤는데 to do list와 그림판까지 만들면 이거를 적용시켜 봐야겠다.