WEB/JavaScript
[크롬 앱 만들기] #8 WEATHER
Harimad
2022. 1. 19. 14:29

weatherAPI: https://home.openweathermap.org
#8.0 Geolocation
geolocation참고: https://devdocs.io/dom/geolocation/getcurrentposition
function onGeoOk(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
alert(`You live in ${lat} ${lng}`);
}
function onGeoError() {
alert(`Can't find you. No wather for you.`);
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
//You link in 37.54... 127.08...
#8.1 Weather API
fetch참고 : https://devdocs.io/dom/fetch
const weather = document.querySelector('#weather span:first-child');
const city = document.querySelector('#weather span:last-child');
const API_KEY = '2987c8637eaa35497d222f12170acb5d'; //my API key
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}&appid=${API_KEY}&units=metric`;
fetch(url)
.then((response) => response.json())
.then((data) => {
city.innerText = data.name;
weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
})
// alert(`You live in ${lat} ${log}`);
}
function onGeoError() {
alert(`Can't find you. No wather for you.`);
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);