카테고리 없음

javascript weather API 이용 (2) - API

고기고기물고기 2022. 4. 7. 07:03

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

 

 

1. 위에 링크를 들어가서 회원가입또는 로그인 해준다

 

회원가입

 

 

2. 로그인 후 API 메뉴 클릭

 

 

 

3. Current Weather Data API 를 찾는다

 

 

4. Weather API 호출하는데 필요한 URL이다

 

5. (1) 에서 받아온 lat 위도, lon 경도로 넘겨주고 API Key는 MY API keys 에서 받아오면 된다!!

 

 

 

6. 해당 정보를 받고 코드를 작성해보자

 

 

const API_KEY = ""; // API KEY를 넣어주세요

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

    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&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;
        weather.innerText = `${data.weather[0].main} / ${data.main.temp}`
    });
}

새 폴더.zip
0.24MB