HTML의 navigator.geolocation 속성은 Geolocation 객체를 반환합니다. 이 객체를 활용하면 브라우저에서 사용자의 현재 위치, 즉 위도(latitude)와 경도(longitude) 좌표를 손쉽게 확인할 수 있습니다.
문법(Syntax)
navigator.geolocation 속성의 기본 사용 문법은 다음과 같습니다.
navigator.geolocation
예제
아래 예제는 버튼을 클릭하면 getCurrentPosition() 메서드를 통해 사용자의 위치 정보를 가져오고, 그 결과를 화면에 출력하는 코드입니다.
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 20px;
width: 330px;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
.show {
font-size: 1.2rem;
color: #fff;
}
</style>
<body>
<h1>HTML navigator geolocation property Demo</h1>
<button class="btn" onclick="display()">Display your position</button>
<div class="show"></div>
<script>
function display() {
var userLocation = navigator.geolocation;
userLocation.getCurrentPosition(displayPosition);
}
function displayPosition(pos) {
document.querySelector(".show").innerHTML = "<p>Your latitude coordinate is: " + pos.coords.latitude + "</p>" + "<p>Your longitude coordinate is: " + pos.coords.longitude + "</p>"
}
</script>
</body>
</html>실행 결과(Output)

화면의 “Display your position” 버튼을 클릭해 보세요. 그러면 아래와 같이 사용자의 현재 위치 좌표가 표시됩니다.

참고 사항
Geolocation API를 사용할 때는 몇 가지 주의할 점이 있습니다.
- 보안 연결 필수: 대부분의 최신 브라우저는 HTTPS 환경에서만 지리적 위치 기능을 허용합니다.
- 사용자 권한 요청: 위치 정보에 접근하려면 반드시 사용자의 동의가 필요하며, 브라우저가 권한 승인 창을 표시합니다.
- 오류 처리 권장:
getCurrentPosition()의 두 번째 인수로 오류 콜백 함수를 전달하면, 권한 거부나 위치 확인 실패 등의 상황에 대응할 수 있습니다.