초보 개발자의 일기
JS weather 본문
728x90
function onGeoOk(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
console.log("You live in", lat, lng);
}
function onGeoError() {
alert("Can't find you. No weather for you");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
이 코드를 이용해 우리의 현재 위치를 알 수 있다.
navigator.geolocation.getCurrentPosition ( )
이때 getCurrentPosition 은 2개의 argument가 필요하다. 앞쪽에는 모든 게 잘 됐을 때 실행될 함수인 onGeoOk 함수를, 뒤에는 실패했을 때 실행될 함수인 onGeoError 함수를 입력한다.
전체 코드
const API_KEY = "ac27e39306ec5ed064e766244c672e97";
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);
728x90
'Frontend practice > java script' 카테고리의 다른 글
callback 함수 (1) | 2022.05.12 |
---|---|
함수 선언 방법 (0) | 2022.05.12 |
JS To Do list 2 (0) | 2022.05.04 |
JS ToDo List 만들기 (0) | 2022.05.04 |
JS quote & background (0) | 2022.05.03 |