weather.js
onst API_KEY = "84d3c253a51da3b6..."
function onGeoOk (position) {
const lat = position.coords.latitude
const lng = position.coords.longitude
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 weatehrCon = document.querySelector("#weather span:first-child")
const cityCon = document.querySelector("#weather span:last-child")
cityCon.innerText = data.name
weatehrCon.innerText = `${data.weather[0].main} / ${data.main.temp}`
})
}
function onGeoErr () {
alert("Can't find you")
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoErr)
Navigator 인터페이스는 사용자 에이전트의 상태와 신원 정보를 나타내며, 스크립트로 해당 정보를 질의할 때와 애플리케이션을 특정 활동에 등록할 때 사용한다. Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져온다. 따라서 위 구문을 통해 사용자 현재 위치 사용 동의를 받고 현재 위치를 가져온다. 위치를 가져왔다면 api weather 사이트에서 현재 위치 날씨 정보를 가져오는 json 형식의 인터페이스를 불러온다. 불러온 정보에서 날씨와 위치를 가져와 화면에 출력한다. Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공한다.
실행화면