바닐라JS - 위치

김현수·2022년 8월 28일

바닐라JS

목록 보기
16/17

Geolocation

현재 내 위치의 위도와 경도 받아오기

navigator.geolocation.getCurrentPosition(성공했을 때 실행할 함수, 에러났을 때 실행할 함수);
function onGeoOk(position) { //js는 argument 1개를 넘겨준다.
    //이 argument에는 위도, 경도 값이 들어있다.
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
}

function onGeoError() {
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

api를 받아와 현재 날씨와 지역 나타내기

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}`
    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);

0개의 댓글