
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작업... 경희씨 책을 다시 들여다봐야겠다
반응형
'개발 > Javascript' 카테고리의 다른 글
[Javascript] filter(), include() 내장객체로 배열 중복값 추출하기 (0) | 2022.09.26 |
---|---|
[Javascript] 전역환경 레코드와 호이스팅. 왜? (0) | 2022.09.13 |
[Javascript] Execution Context (실행 컨텍스트) (0) | 2022.09.02 |
[Javascript] 호이스팅(hoisting)이란? 왜? (4) | 2022.08.31 |
[React] Props vs State (0) | 2022.08.27 |