onGeoOk
함수
- 위도와 경도, api url을 저장하는 변수
- 날씨와 도시를 표시
onGeoError
함수
- 위치를 부르는게 에러가 났을때 실행하는 함수
코드 - weather.js
const API_KEY = "e83cf8d4a4d3d08de250fbab8e92be42"
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 => {
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.")
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
정리
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
fetch(url).then(response => response.json())