# Weather

Doozuu·2022년 11월 1일
0

Javascript

목록 보기
7/99

1. Geolocation

⭐️ 내 현재 위치를 얻을 수 있는 함수

navigator.geolocation.getCurrentPosition(잘 됐을 때 실행될 함수, 에러났을 때 실행할 함수);
-> 결과로 object 반환

function onGeoOk(position){
const lat = position.coords.latitude; // 위도 얻기
const lon = position.coords.longitude; // 경도 얻기
console.log("You live in", lat, lon);
}
function onGeoError(){
alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);


2. Weather API

https://openweathermap.org

주소창에 아래 링크 입력

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={APIkey}

  • lat, lon : 위에서 구한 위도와 경도 입력
  • API key : 사이트 프로필에 있는 API key 입력

👉🏻 coords, weather 등을 얻을 수 있다.


⭐️ fetch는 promise이다.

  • promise : 당장 뭔가 일어나지 않고 시간이 좀 걸린 뒤에 일어나는 것.
  • 따라서 정보가 나타나기 까지 로딩 시간이 조금 걸림.
const API_KEY = "my API key";

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    console.log("You live in", lat, lon);
    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 weatherContatiner = document.querySelector("#weather span:first-child")
        const cityContatiner = document.querySelector("#weather span:last-child")
        cityContatiner.innerText = data.name; 
        weatherContatiner.innerText = data.weather[0].main;
    });
}
function onGeoError(){
    alert("Can't find you. No weather for you.");
}
    
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

실행화면 (날씨, 장소)



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

profile
모든게 새롭고 재밌는 프론트엔드 새싹

1개의 댓글

comment-user-thumbnail
2024년 3월 16일

I'm in Colombia right now. I didn't expect the weather to change so quickly here and now I have to keep an eye on the weather forecast. By the way, I'm glad I found this https://tiempo.info/colombia weather forecast site because it is the most accurate and has only up-to-date weather information. You can see for yourself that now this site has become the best assistant for me. Pay attention to it

답글 달기