[TIL] JS: 바닐라 JS로 크롬 앱 만들기 04

송나은·2021년 1월 29일
0

JavaScript

목록 보기
10/23
post-thumbnail

크롬 앱 만들기

5. 날씨

⭐ 위치 좌표(위도, 경도)를 가져와서 저장하기
⭐ 날씨(온도), 위치 나타내기

  • navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError) 위치정보 조회 여부 묻는다.
  • position.coords.latitudeposition.coords.longitude로 위도와 경도를 가져왔다.
  • API URL을 호출하여 데이터를 얻을 수 있다.
const waather = document.querySelector(".js-weather");
// 내 고유 KEY 적는 곳
const API_KEY = ""
const COORDS = 'coords';

function getWeather(lat, lng){
    // 데이터를 가져오는 방법.
    fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude={part}&appid=${API key}`)
    // .then 기다리는 함수. 함수가 데이터를 가져온 다음 실행할 수 있도록 한다.
    .then(function(response){
        return response.json();
    })
    .then(function(json){
        const temperature = json.main.temp;
        const place = json.name;
        weahter.innerText = `${temperature} @ ${place}`;
    });
}


function saveCoords(coordsObj){
    localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function handleGeoSucces(position){
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    const coordsObj = {
        latitude,
        longitude
    };
    saveCoords(coordsObj);
}

function handleGeoError(){
    console.log("Cant access geo location");
}
function askForCoords(){
    navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError)
}

function loadCoords(){
    const loadedCords = localStorage.getItem(COORDS);
    if(loadedCoords === null){
        aksForCoords();
    } else {
        const parseCoords = JSON.parse(loadCoords);
        getWeather(parseCoords.latitude, parseCoords.longitude);
    }
}
function init(){

}
init();

✔ openweathdrmap.org 바로가기

profile
그때그때 공부한 내용과 생각을 기록하는 블로그입니다.

0개의 댓글