profile image

L o a d i n g . . .

Weather API - OpenWeatherMap

Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.

openweathermap.org


function onGeoOk(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    console.log(`현재 위치는 ${lat}, ${lon}`)
}

function onGeoError() {
    alert("날씨를 제공할 위치를 찾을 수 없습니다.")
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

내장함수인 geolocation을 사용해서 현재 좌표를 뽑아냈다.

이제 이 위도 경도를 사용해서 현 위치의 날씨를 찾아낼 것이다.




weather API에 들어가면 대기오염, 날씨 등등 다양한 API정보를 가져올 수 있다.
그중 왼쪽에있는 Current Weather Data를 사용해보자

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

검색창에 조건에 맞추어서 API를 호출했다

쨔쟌



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

API key를 상수로 등록해주고 위도 경도를 url에 입력해준 후 콘솔창으로 코드 출력시 제대로 뜨나 다시확인

한국, 용산까지 잘 뜬다.





콘솔이 아닌 fetch를 사용해 네트워크에서 URL확인



매개변수 확인후 units에서 화씨를 섭씨로 바꾸고 lang 한국어로 설정해주었다.

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}&lang=kr&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].description} / ${data.main.temp}`
        });
}

function onGeoError() {
    alert("날씨를 제공할 위치를 찾을 수 없습니다.")
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);



남은건 css작업... 경희씨 책을 다시 들여다봐야겠다

반응형
복사했습니다!