navigator wep API 를 활용하여 현재 위치를 가져온다,
* API 란?
API(Application Programming Interface, 응용 프로그램 프로그래밍 인터페이스)는 응용 프로그램에서 사용할 수 있도록, 운영 체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있게 만든 인터페이스를 뜻한다.

프로그램들이 서로 상호작용하는 것을 도와주는 매개체라고 볼 수 있다.
const weather = document.querySelector(".js-weather");
function saveCoords(coordsObj) {
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
//localstorage의 key, value 값은 모두 string 타입으로 저장되기때문에 변환시켜준다.
}
function handleSuccess(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = { // 객체의 key, value 값이 동일할 때에는 한번만 써줘도 된다.
latitude, // localStorage에 객체로 value에 저장하기위해서 객체에 넣어준다.
longitude
};
saveCoords(coordsObj); // localStorage에 위치 저장
}
function handleError() {
console.log('cant not access to location');
}
function askForCoords() {
navigator.geolocation.getCurrentPosition(handleSuccess, handleError);
}
function loadCoords() {
const loadedCoords = localStorage.getItem(COORDS);
if(loadedCoords === null) {
// localStorage에 좌표값이 저장되어있지않다면
askForCoords(); // 좌표값을 물어본다
}
}
function init() {
loadCoords();
}
init();
Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.
구문

-success : 받아온 현재 위치 GeolocationPosition 객체를 유일한 매개변수로 받는 콜백 함수.
-error : 위치를 받아오지 못했을 경우, GeolocationPositionError 객체를 유일한 매개변수로 받는 콜백 함수.
Geolocation.getCurrentPosition() 로 정상적으로 위치를 가져왔을 경우, console.log로 현재 위치를 확인해보면,
아래와 같이 가져온 현재 위치를 확인할 수 있다. 객체로 위치가 저장되어있다.

위도와 경도 값을 얻기 위해서 아래와 같이 success 콜백 함수인, handleSuccess 함수를 정의해준다.
function handleSuccess(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = { // 객체의 key, value 값이 동일할 때에는 한번만 써줘도 된다.
latitude, // localStorage에 객체로 value에 저장하기위해서 객체에 넣어준다.
longitude
};
saveCoords(coordsObj); // localStorage에 위치 저장
}
추후 다음 단계에서 현재 위치를 기준으로 날씨를 가져오기 위해서 현재 좌표계(coord)를 local storage에 저장해준다. saveCoords ();
*localStorage 란 ?
화면 이동이 있거나 영구적으로 저장해야 하는 경우 DB에 저장을 하거나 임시적으로 저장하고 싶은 경우 쿠키(cookie)를 사용하기도 합니다.
이처럼 일정 시간 또는 영구적으로 값을 저장하고 싶은 경우에 사용할 수 있는 것이 WebStorage API인 로컬 스토리지(LocalStorage)가 있습니다.
페이지가 종료되도 저장된 값이 사라지지 않아 영구적으로 사용가능하다.
- key, value 값이 하나의 세트로 저장된다.
- 값은 반드시 string(문자열)로 저장된다. (중요!)
const COORDS = 'coords';
function saveCoords(coordsObj) {
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
//localstorage의 key, value 값은 모두 string 타입으로 저장되기때문에 변환시켜준다. number -> string
}
localStorage의 경우 값이 모두 string 으로 저장되기 때문에 위에서 가져온 coordsObj 은 현재 number이므로
JSON.stringify를 사용하여 number 을 string으로 변환시켜준 후 저장해준다.
* JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다.
'잡다한 메모' 카테고리의 다른 글
[JavaScript] 삼항연산자 (ternary operator) (0) | 2020.05.21 |
---|---|
[JavaScript] fetch API 이해과 개념 / .then() (0) | 2020.05.21 |
[JavaScript] 현재 시간 및 날짜 가져오기 : new Date(); (0) | 2020.05.15 |
Github-git push 실행시 오류 해결방법 (failed to push some refs to~) (0) | 2020.05.08 |
Github - git push 실행 시 오류 해결방법 ('origin' doest not appear to be a git repsitory) (0) | 2020.05.08 |