공부기록/[강의노트] 바닐라 JS로 크롬 앱 만들기

바닐라 JS로 크롬 앱 만들기 #8.0~#8.2

Jenner 2022. 4. 22. 02:03

#8.0 Geolocation

브라우저에서 사용자의 위치를 가져오기 위해 

navigator.geolocation.getCurrentPosition() 함수를 사용한다.

 

navigator.geolocation.getCurrentPosition(success, error, [options])

geolocation의 syntax이다. (출처 MDN)

 

function onGeoOk(position){
    console.log(position)
;}

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

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

이렇게 입력하고 브라우저 창을 새로고침 하면

 

위와 같은 화면이 나온다. 

함수 다섯 줄로 사용자의 위도와 경도를 알 수 있게 되었다. 

 

GeoLocationPosition의 왼쪽 화살표를 클릭해 보면

위와 같은 화면이 나온다. 

그러므로 내 위도와 경도 정보를 얻을 수 있는 위치는 

 

coords.latitude

coords.longitude

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    console.log("You live in", lat, lon);

}

위 사진이 console창에 뜬 결과이다. 

 

이제 나의 위도와 경도 숫자값을 바꿔줄 API가 필요하다. 

 

 

#8.1 Weather API

 

https://openweathermap.org/ 방문,

 

Sign in해주고, 

그림과 같이 순서대로 클릭 

내 경도와 위도의 날씨를 알 수 있다. 그리고 내 위도와 경도의 지역명을 얻어낼 수 있다. 

 

function onGeoOk(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}`
    fetch(url);

}

이렇게 하면 사용자의 위도와 경도를 가지고 올 수 있으며 

fetch(url)을 통해 나 대신 javascript가 url을 가지고 와준다. 

 

(아래 모습이 네트워크에서 가져온 값)

 

 

 

여기서 내가 있는 곳의 name, 그리고 temp를 가지고 오고 싶다.  

그런데 temp의 값이 화씨이다. 우리는 일반적인 섭씨를 얻고 싶다. 

 

그러려면 

 

 

여기의 units에서 metric값을 가져오면 된다. 

url에 &units=metric 를 추가해준다.

 

fetch는 promise인데 그것은 당장 일어나지 않고 나중에 일어나는 것이다. 

url을 fetch하고 그다음으로 response를 받는다. 

 

 

function onGeoOk(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 span:first-child")
        const city = document.querySelector("#weather span:last-child")
        city.innerText = data.name;
        weather.innerText = data.weather[0].main;
    });

}​

입력을 하고 나니 

 

이렇게 결과창이 떴다. 

 

 

#8.2 Conclusions

 

Thank you!!!!