반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

js) WEATHER 본문

노마드 코더/바닐라 JS로 크롬 앱 만들기

js) WEATHER

5_hyun 2022. 5. 2. 23:41
function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    console.log("You live in", lat, lng);
}
function onGeoError(){
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

user의 위치(geolocation)를 알려주는 것이다. navigator와 geolocation, getCurrentPosition을 사용한다. 이걸 부르면 브라우저에서 정보를 준다. 와이파이, GPS, 위치 등을 준다.

 

getCurrentPosition은 2개의 인자가 필요하다. 하나는 성공시 실행될 함수, 하나는 에러가 발생했을 때 실행하는 함수이다.

그 두 함수를 OnGeoOk와 OnGeoError로 만들어줬다.

 

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Leaving everything behind, people are fleeing conflict in Ukraine. They need shelter, food, and water. When you subscribe to our service, you can join us to help with donation of just of 20. Openweather will add 40 to each donation and send it to Disastrou

openweathermap.org

그리고 이 사이트에 들어가 회원가입을 하고 current weather date API를 이용한다.

 

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}이 주소에 들어가면 그 지역 날씨를 알 수 있다.

 

저 주소에 들어가면 이렇게 정보가 뜬다.

 

const API_KEY = "내 정보에서 나오는 키 값";

function onGeoOk(position){
    const lat = position.coords.latitude;
    const log = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${log}&appid=${API_KEY}`;
    fetch(url);
}
function onGeoError(){
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

API_KEY에는 키 값을 넣어준다. 그리고 fetch()를 이용하면

Network에 가면 맨 마지막 줄에 JS가 fetch를 사용해서 URL을 요청했다.

 

const API_KEY = "API 값";

function onGeoOk(position){
    const lat = position.coords.latitude;
    const log = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${log}&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} / ${data.main.temp}`;
    });//promise는 당장 뭔가 일어나지 않고 시간이 좀 걸린 뒤 일어난다.
    //url에 나오는 모든 내용이 JSON이다.
}   
function onGeoError(){
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

저렇게 요청을 한 상태에서 html에 id가 weather인 div를 만들고 span을 넣는다. 그리고 url에서 정보를 가져와서 span에 넣어준다.

 

이렇게 지역과 날씨가 나오게 된다.

728x90
반응형

'노마드 코더 > 바닐라 JS로 크롬 앱 만들기' 카테고리의 다른 글

챌린지 4일차  (0) 2022.05.12
classList 메소드  (1) 2022.05.05
js) To Do List-Deleting To Dos  (0) 2022.05.02
js) To Do List-Loading To Dos  (0) 2022.04.30
js) QUOTES AND BACKGROUND  (1) 2022.04.29
Comments