• 코드:
​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>구글 맵을 통한 사용자의 위치 표시</h1>
12
​
13
    <button onclick="findLocation()">사용자의 위치 표시</button>
14
    <p id="myLocation"></p>
15
    <div id="mapLocation"></div>
16
​
17
    <script>
18
        var loc = document.getElementById("myLocation");
19
        function findLocation() {
20
            if (navigator.geolocation) {
21
                navigator.geolocation.getCurrentPosition(showYourLocation, showErrorMsg);
22
            } else { 
23
                loc.innerHTML = "이 문장은 사용자의 웹 브라우저가 Geolocation API를 지원하지 않을 때 나타납니다!";
24
            }
25
        }
26
​
27
        function showYourLocation(position) {
28
            var userLat = position.coords.latitude;
29
            var userLng = position.coords.longitude;
30
            var imgUrl = "http://maps.googleapis.com/maps/api/staticmap?center=" + userLat + "," + userLng + "&zoom=15&size=500x400&sensor=false";
31
            document.getElementById("mapLocation").innerHTML = "<img src='"+imgUrl+"'>";
32
        }
33
​
34
        function showErrorMsg(error) {
35
            switch(error.code) {
36
                case error.PERMISSION_DENIED:
37
                loc.innerHTML = "이 문장은 사용자가 Geolocation API의 사용 요청을 거부했을 때 나타납니다!"
38
                break;
39
                case error.POSITION_UNAVAILABLE:
40
                loc.innerHTML = "이 문장은 가져온 위치 정보를 사용할 수 없을 때 나타납니다!"
41
                break;
42
                case error.TIMEOUT:
43
                loc.innerHTML = "이 문장은 위치 정보를 가져오기 위한 요청이 허용 시간을 초과했을 때 나타납니다!"
44
                break;
45
                case error.UNKNOWN_ERROR:
46
                loc.innerHTML = "이 문장은 알 수 없는 오류가 발생했을 때 나타납니다!"
47
                break;
48
            }
49
        }
50
    </script>
51
​
52
</body>
53
​
54
</html>