본문 바로가기

카테고리 없음

JS #11- 웹 API 1 (BOM, DOM)

Location 객체

 

 

Navigator 객체
const { platform, userAgent, language, onLine, geolocation } = navigator;

navigator.geolocation.getCurrentPosition((data) => { //위치를 찾음
    console.log(data)
})

 

위도, 경도 콘솔에 출력하기 

 
const { platform, userAgent, language, onLine, geolocation } = navigator;

navigator.geolocation.getCurrentPosition((data) => { //위치를 찾음
    const {latitude:lat, longitude:long} = data.coords;
    console.log({lat, long})
})

 

브라우저에 요청하고 요청된 값을 받아오기 때문에 시간이 걸린다. 

바로 return을 해주면 값이 들어오기도 전에 값을 return 해주기 떄문에!

값을 return해주려면 settimeout 비동기 처리를 해주어야 한다. 

 

--> 사용자의 환경에 따라 걸리는 시간이 다를 수 있으니 "CALL BACK" 방식을 사용해보자

 

*비동기적인 데이터를 꺼내기 위해서!

*안쪽에 있는 함수를 만든다! 

ㄴ> 함수는 인자로 전달할 수 있는데, 인자가 완벽하게 들어갈 수 있을 떄까지, 즉 값이 들어올때까지 기다릴 수 있는 것이다!

 

 

안전하게 lat과 long을 받아온 이후에 ~ 실행을 하는 것이다. 

사실 success라는 함수는 callback 기능만 수행하는 것이다! 

 

 

마지막으로 전달되는 함수에서 출력하는 기능까지 실행하면 완료

물론 success라는 함수를 따로 정의할 수 있지만 간단하게 매개변수로 넘겨버리는 것이다.

 

**Promise 구문을 이용해서 깔끔하게 표현할 수 있다! 가장깔끔**

function getCoords(){

    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition((data)=>{
        if(data){
          const { latitude:lat, longitude:long } = data.coords;
          resolve({lat,long})
        }else{
          reject({message:'error!'})
        }
      })
    })
   
  }

 

 

결론 : 윈도우에서 요청해서 가져오는 데이터에는 일정 시간이 필요하다.