자바스크립트 geolocation과 OpenWeather API 사용하기

버건디·2022년 10월 11일
0

자바스크립트

목록 보기
18/31
post-thumbnail

🔍 getCurrentPosition 을 이용하여 현재 위치 가져오기


document.addEventListener('DOMContentLoaded', () => {

    const temp = document.getElementById('temp'); // 기온 span 창
    const location = document.getElementById('location'); // 위치 location 창
    navigator.geolocation.getCurrentPosition(success, err);
})

자바스크립트 내에 있는 navigator 객채에서 getCurrentPosition 함수를 이용하면 현재 내가 있는 위도와 경도를 얻을 수 있다.

getCurrentPosition 함수 내에서는 위치를 얻었을때 성공할 함수와, 위치 정보를 얻지 못했을때 띄울 에러 함수 두개의 콜백 함수를 갖는다.

document.addEventListener('DOMContentLoaded', () => {

    const temp = document.getElementById('temp'); // 기온 span 창
    const location = document.getElementById('location'); // 위치 location 창


    navigator.geolocation.getCurrentPosition(success, err);

    
    //성공했을때

    function success(pos){
        const lat = pos.coords.latitude;
        const lon = pos.coords.longitude;
        console.log(lat); 
        console.log(lon);
    }

    //에러 났을때

    function err(){
        console.log('Error!');
    }
})

위도와 경도가 성공적으로 출력된 것을 볼 수 있다.


🔍OpenWeather API 사용하기

OpenWeatherAPI 사이트에 들어가서 회원가입을 하면 API KEY를 발급 받을수 있다. 또한 API 창으로 가면 필요한 API 에 대한 문서들을 얻을 수 있다.

Current Weather API를 들어가면 사용 방법이 자세히 적혀 있는데, API call 이라고 적혀있는 주소에 getCurrentPosition을 통해 얻은 위도와 경도, 그리고 API KEY를 적어주면 된다.

document.addEventListener('DOMContentLoaded', () => {

    const temp = document.getElementById('temp'); // 기온 span 창
    const location = document.getElementById('location'); // 위치 location 창

    const lat = 37.413582;
    const lon = 126.9089751;
    const API_KEY = "사이트에서 얻은 API KEY"

    const URL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`
})

위의 URL로 접속하면 JSON 형태의 현재 위치에 해당되는 날씨의 데이터들에 접근할 수 있다.

document.addEventListener('DOMContentLoaded', () => {

    const URL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`

    fetch(URL).then(res => res.json()).then(data => console.log(data.main.temp));
    
})

받은 응답을 json화시켜서 데이터를 출력하니 저 URL에 있는 데이터를 가져올 수 있었다.

   fetch(URL)
   .then(res => res.json())
   .then(data => {
    const nowTemp = Math.floor(data.main.temp) - 273;
    const nowLocation = data.name;
    temp.innerText = nowTemp;
    location.innerText = nowLocation;
   });

기온을 깔끔하게 나타내기 위해서 소수점을버리고 273을 빼주었고, 위치를 나타내기 위해서 name 속성을 가져와서 innerText 안에 넣어주었다.

브라우저 창에 잘 나타난다.

profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글