보라코딩
자바스크립트로 날씨 본문
코드가 엄청 심플해서 놀랐다!
유용한 코드라 생각해서 기록하기 :)
날씨 API는 아래 사이트 참고하기!
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
weather.js
const API_KEY = "키를 넣으시오~~~";
function onGeoSuccess(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
console.log("너 여기 살아!", 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} / ${data.main.temp}`;
});
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
console.log(navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError));
'코딩 > HTML5, CSS3, JS' 카테고리의 다른 글
노마드코더 자바스크립트 강의 _ ToDoList JS 코드 (0) | 2023.09.19 |
---|---|
JS 모듈화, ajax (어렵..) (1) | 2023.05.16 |
Day60_230323_ jQuery 끝 (0) | 2023.03.23 |
Day59_230322_ jQuery (animate) (0) | 2023.03.22 |
Day58_230321_ jQuery (setInterval, fadeiIn, prepend, empty) (0) | 2023.03.21 |