아래 코드의 내가 작성한 API key는 당연히 무효함.
<script>
const API_KEY = "2i2910a3m2we8a77th79er79ap20i59";
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 p:first-child");
const city = document.querySelector("#weather p:last-child");
city.innerText = `${data.name}`;
weather.innerText = `${data.weather[0].main} / ${data.main.temp}℃ @ `;
});
}
function onGeoErr() {
alert("사용자의 위치를 파악할 수 없습니다.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoErr);
</script>
디바이스의 현재 위치를 가져온다.(latitude, longitude ...)
Parameters?
(success, error): 성공했을 때의 callback 함수, 에러가 났을 때의 callback 함수
- success : A callback function that takes a GeolocationPosition object as its sole input parameter.
- error : An optional callback function that takes a GeolocationPositionError object as its sole input parameter.
우선 위의 코드 상에서는 fetch 함수의 인수로 받아올 날씨 정보의 url을 지정하고, 응답된 JSON 데이터를 화면에 입혀주는 방식인 것 같다. fetch API는 잠깐 나온 거라 나중에 필요하거나 궁금할 때 다시 찾아보기 위해 기록했다.
💡 네트워크 통신을 포함한 리소스를 가지고 오기 위한 인터페이스를 제공해주는 보다 새로운 API.
XMLHttpRequest와 기능은 같지만, 확장 가능하며 효과적으로 구성되어 있기 때문에 강력하고 유연한 조작이 가능하다.
Fetch에는 네트워크 요청⋅응답과 관련된 일반적인 오브젝트로 Request와 Response가 포함되어 있다.
fetch() 함수를 사용하는 경우에는 가져올 리소스의 경로를 인수로 반드시 지정해야 한다.