💡about API
API 는 특정 웹사이트로부터 데이터를 얻거나 컴퓨터끼리 소통하기 위해 고안된 것 = api에는 디자인이 필요 없음. JS에서는 API를 이용해 새로고침 없이 데이터를 가져올 수 있음.
JS는 웹사이트로 request를 보내고 응답을 통해 데이터를 얻을 수 있는데, 이 데이터를 적용시키는 과정에서 refresh가 필요 없음. JS가 보이지 않는 곳에서 끊임없이 데이터를 가져오고 있음 (이메일창도 같은 원리)
< span class = "js-weather" >
const weather = document.querySelector("js-weather");
function loadCoords(){
const loadCords = localStorage.getItem(COORDS);
if (loadCoords === null) {
askForCoords();
} else {
const parseCoords JSON.parse(loadCoords);
// localStorage에는 string 형태로 저장되어 있기 때문에 JSON으로 변환
}
}
navigator.geolocation.getCurrentPosition
메서드를 실행, 브라우저가 실행중인 장치의 위치정보를 조사해 객체로 반환합니다.navigator.geolocation.getCurrentPosition()
💡 naviatgor :
navigator 객체는 브라우저 공급자 및 버전 정보 등을 포함한 브라우저에 대한 다양한 정보를 저장하는 객체입니다.
https://developer.mozilla.org/ko/docs/Web/API/Navigator
💡 geolocation :
Geolocation 인터페이스는 장치의 위치를 가져오는 방법을 나타냅니다. Geolocation을 사용하면 웹 사이트나 웹 앱이 위치 정보를 활용해, 현재 위치에 대해 맞춤 콘텐츠를 제공할 수 있습니다.
https://developer.mozilla.org/ko/docs/Web/API/Geolocation
💡 geolocation.getCurrentPosition() :
Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.
https://developer.mozilla.org/ko/docs/Web/API/Geolocation/getCurrentPosition
getCurrentPosition을 실행하면 성공과 실패 두가지 경우의 수가 있고, 그 외 옵션이 존재합니다. 기본적으로 성공과 실패 시의 함수를 필수로 요구 하기 때문에 함수를 각각 작성해줍니다.
포지션을 가져오는 데 성공한 경우, 포지션의 위도, 경도값을 배열에 입력합니다.
// 포지션을 가져오는 데 성공한 경우
function handleGeoSucess(position){
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = {
latitude,
longitude
};
💡 배열은 보통 key : value를 매치하는게 기본이지만,
const coordsObj = { latitude : latitude, longitude : longitude };
key값과 value의 변수 값이 같다면 아래와 같이 저장할 수 있습니다.
const coordsObj = { latitude, longitude };
// 포지션을 가져오는 데 실패한 경우
function handleGeoError(position){
console.log('Cant acess geo location');
}
JSON.stringify
를 이용, 문자열로 변환하여 저장합니다.function saveCoords(coordsObj){
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
const API_KEY = "~"
fetch
메서드를 사용합니다.function getWeather(lat, lng) {
fetch (`API 주소 `); // 데이터를 얻기 위해 fetch를 사용해준다.
}
function handleGeoSucess(position){
// 포지션을 가져오는 데 성공한 경우 처리 함수
};
saveCoords(CoordsObj);
getWeather(latitude, longitude);
// 코드배열을 localStorage에 저장하고 날씨데이터에 위도, 경도 삽입
}
function loadCoords(){
const loadCords = localStorage.getItem(COORDS);
if (loadCoords === null) {
askForCoords();
} else {
const parseCoords JSON.parse(loadCoords);
// localStorage에는 string 형태로 저장되어 있기 때문에 JSON으로 변환
getWeather(parseCoords.latitude, parseCoords.longitude);
// 날씨데이터에 위도, 경도 삽입
}
}
function getWeather(lat, lng) {
fetch (`API 주소 `);
.then(function(response){
return response.json(); //response에는 network정보만 보이므로 JSON(javascript Object)를 가져오도록 한다.
})
.then(function(json) { // 그리고 JSON Data가 준비되면 Json에서 이것저것을 가져온다.
const temperature = json.main.temp;
const place = jsom.name;
weather.innerText ``${temperature} @ ${place};
});
}