• 코드:
​x
 
1
<!DOCTYPE html>
2
<html lang="ko">
3
​
4
<head>
5
    <meta charset="UTF-8">
6
    <title>HTML5 API Geolocation</title>
7
</head>
8
​
9
<body>
10
​
11
    <h1>geolocation에서의 오류 처리</h1>
12
​
13
    <button onclick="findLocation()">현재 위치의 위도와 경도</button>
14
    <p id="myLocation"></p>
15
​
16
    <script>
17
        var loc = document.getElementById("myLocation");
18
        function findLocation() {
19
            if (navigator.geolocation) {
20
                navigator.geolocation.getCurrentPosition(showYourLocation, showErrorMsg);
21
            } else { 
22
                loc.innerHTML = "이 문장은 사용자의 웹 브라우저가 Geolocation API를 지원하지 않을 때 나타납니다!";
23
            }
24
        }
25
​
26
        function showYourLocation(position) {
27
            loc.innerHTML = "현재 사용자는 위도 " + position.coords.latitude + ", 경도 " + position.coords.longitude + "에 위치하고 있습니다.";    
28
        }
29
​
30
        function showErrorMsg(error) {
31
            switch(error.code) {
32
                case error.PERMISSION_DENIED:
33
                loc.innerHTML = "이 문장은 사용자가 Geolocation API의 사용 요청을 거부했을 때 나타납니다!"
34
                break;
35
                case error.POSITION_UNAVAILABLE:
36
                loc.innerHTML = "이 문장은 가져온 위치 정보를 사용할 수 없을 때 나타납니다!"
37
                break;
38
                case error.TIMEOUT:
39
                loc.innerHTML = "이 문장은 위치 정보를 가져오기 위한 요청이 허용 시간을 초과했을 때 나타납니다!"
40
                break;
41
                case error.UNKNOWN_ERROR:
42
                loc.innerHTML = "이 문장은 알 수 없는 오류가 발생했을 때 나타납니다!"
43
                break;
44
            }
45
        }
46
    </script>
47
​
48
</body>
49
​
50
</html>