HTML Geolocation은 사용자가 허용하는 경우에만 사용자의 실시간 지리적 위치를 얻는 데 사용됩니다. 다양한 이유로 사용할 수 있습니다. JavaScript를 사용하여 위도와 경도를 가져옵니다.
참고 − Chrome 50 이전에는 지리적 위치 요청이 승인될 수 있었지만 Chrome 50에서는 HTTPS를 통한 요청만 승인되고 HTTP를 통한 요청은 무시되었습니다.
구문
다음은 구문입니다 -
navigator.geolocation.getCurrentPosition()
여기에서 getCurrentPosition()에 의해 반환된 객체 다음 속성을 가질 수 있습니다 -
| 속성 | 반환 값 |
|---|---|
| coords.latitude | 십진수로 표시된 지리적 위도 |
| 좌표.경도 | 십진수로 표시된 지리적 경도 |
| coords.accuracy | 위치의 정확도 |
| 좌표.고도 | 평균 해발 고도(미터) |
| coords.altitudeAccuracy | 위치의 고도 정확도 |
| coords.heading | 북쪽에서 시계 방향으로 도 단위로 진행 |
| coords.speed | 초당 미터의 속도 |
| 임스탬프 | 응답 날짜/시간 |
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> 1) 버튼을 클릭하기 전에 -

2) '검색 클릭 후 ' 버튼 -

3) '위치 업데이트 클릭 후 ' 버튼 -

4) '검색 클릭 후 ' 버튼 -

5) '위치 업데이트 클릭 후 ' 버튼 및 사용자가 위치 액세스 권한을 거부 -
