본문 바로가기
JavaScript

[JavaScript] 현재 위치 받아오기

by teamnova 2022. 3. 12.

자바스크립트에서 user의 위치(geolocation)을 주는 함수를 사용해서 사용자의 위치를 받아오는 코드를 짜보겠습니다.

 

navigator.geolocation.getCurrentPosition() 메서드를 사용하면 브라우저에서 위치 좌표를 리턴합니다.

 

 

위에서 보이는 것과 같이 getCurrentPosition메서드는 인자 2개를 필요로 합니다.

하나는 성공했을 때 실행할 함수이고, 

나머지 하나는 에러가 발생했을 때 실행할 함수입니다.

 

이렇게 코드로 성공했을 때와 실패했을 때 실행할 콜백함수를 작성해 줍니다.

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    console.log("You live in", lat, lng);
}
function onGeoError(){
    alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

 

그럼 브라우저의 콘솔 창에서 브라우저에서 받아온 사용자의 위도와 경도좌표를 확인할 수 있습니다.