HTML 지리적 위치(Geolocation)란?
HTML 지리적 위치(Geolocation)는 사용자의 명시적인 허가가 있을 때에만 실시간으로 사용자의 지리적 위치를 파악할 수 있는 기능입니다. 지도 기반 서비스, 배달 앱, 날씨 정보 제공, 주변 매장 검색 등 다양한 웹 서비스에서 활용되며, 내부적으로는 JavaScript를 사용하여 위도(latitude)와 경도(longitude) 값을 가져옵니다.
참고: Google Chrome 50 이전 버전에서는 HTTP 환경에서도 지리적 위치 요청이 승인될 수 있었지만, Chrome 50부터는 보안 정책에 따라 HTTPS를 통한 요청만 승인되며 HTTP 요청은 무시됩니다.
기본 문법
지리적 위치 정보를 가져오는 기본 문법은 다음과 같습니다.
navigator.geolocation.getCurrentPosition()
getCurrentPosition() 메서드가 반환하는 객체는 아래와 같은 속성들을 포함합니다.
| 속성 | 반환 값 |
|---|---|
| coords.latitude | 십진수 형태의 지리적 위도 |
| coords.longitude | 십진수 형태의 지리적 경도 |
| coords.accuracy | 위치의 정확도 |
| coords.altitude | 평균 해수면 기준 고도(미터 단위) |
| coords.altitudeAccuracy | 위치의 고도 정확도 |
| coords.heading | 북쪽을 기준으로 시계 방향으로 측정한 방위(도 단위) |
| coords.speed | 초당 미터(m/s) 단위의 이동 속도 |
| timestamp | 응답이 생성된 날짜 및 시간 |
오류 처리 예제
다음 예제는 HTML 지리적 위치 기능에서 발생할 수 있는 다양한 오류 상황을 처리하는 방법을 보여줍니다.
<!DOCTYPE html>
<html>
<head>
<title>HTML Geolocation</title>
<style>
* {
padding: 2px;
margin:5px;
}
form {
width:70%;
margin: 0 auto;
text-align: center;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>HTML-Geolocation</legend>
<input type="button" value="Update Location" onclick="updateLocation()">
<input type="button" value="Search" onclick="searchLoc()">
<div id="divDisplay">Current Location:</div>
<div>
<span id="latitude">Latitude: 42.9177901</span>
<span id="longitude">Longitude: -75.8114698</span>
</div>
<script>
var latObj = document.getElementById("latitude");
var longObj = document.getElementById("longitude");
var divDisplay = document.getElementById("divDisplay");
function searchLoc(){
var lat = latObj.textContent.split(": ")[1];
var long = longObj.textContent.split(": ")[1];
var url = "https://www.google.com/maps/@"+lat+","+long+",8.58z";
browseWindow = window.open(url, "browseWindow", "width=400, height=200");
}
function updateLocation(){
browseWindow.close();
var user = navigator.geolocation;
if (user)
user.getCurrentPosition(updatePosition, errorHandler);
else
divDisplay.textContent = "Geolocation is not supported in this browser";
}
function updatePosition(position) {
divDisplay.innerHTML = 'Location Updated<br>Current Location:';
latObj.textContent = 'Latitude: '+position.coords.latitude;
longObj.textContent = 'Longitude: '+position.coords.longitude;
}
function errorHandler(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
divDisplay.textContent = "You denied the request to get Geolocation"
break;
case error.POSITION_UNAVAILABLE:
divDisplay.textContent = "Your location information is unavailable"
break;
case error.TIMEOUT:
divDisplay.textContent = "The request to get your location timed out"
break;
case error.UNKNOWN_ERROR:
divDisplay.textContent = "Unknown error occurred"
break;
}
}
</script>
</body>
</html>
주요 오류 코드
예제의 errorHandler 함수에서 처리하는 주요 오류 코드는 다음과 같습니다.
- PERMISSION_DENIED: 사용자가 위치 정보 접근 권한 요청을 거부한 경우
- POSITION_UNAVAILABLE: 위치 정보를 사용할 수 없는 경우
- TIMEOUT: 위치 정보 요청이 제한 시간 내에 완료되지 않은 경우
- UNKNOWN_ERROR: 그 외 알 수 없는 오류가 발생한 경우
실행 결과
1) 아무 버튼도 클릭하지 않은 초기 화면 −

2) 'Search(검색)' 버튼 클릭 후 −

3) 'Update Location(위치 업데이트)' 버튼 클릭 후 −

4) 다시 'Search(검색)' 버튼 클릭 후 −

5) 'Update Location' 버튼 클릭 후 사용자가 위치 접근 권한을 거부한 경우 −
