⭐ 위치 좌표(위도, 경도)를 가져와서 저장하기
⭐ 날씨(온도), 위치 나타내기
navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError)
위치정보 조회 여부 묻는다.position.coords.latitude
와position.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();