javascript

[Javascript] 현재위치 gps 구글지도 표시

http://portfolio.wonpaper.net 2024. 2. 18. 22:25

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html>
<head>
    <title>현재 위치 지도 표시</title>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>
 
<h1>현재 위치 지도 표시</h1>
<div id="map"></div>
 
<script>
    // 위치 정보를 받아오고 지도에 표시하는 함수
    function showMap(position) {
        // 현재 위치의 위도와 경도
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        
        // Google Maps API를 이용하여 지도 표시
        var mapOptions = {
            center: {lat: latitude, lng: longitude},
            zoom: 15
        };
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);
        
        // 마커 생성하여 현재 위치 표시
        var marker = new google.maps.Marker({
            position: {lat: latitude, lng: longitude},
            map: map,
            title: '현재 위치'
        });
    }
 
    // 위치 정보를 가져오는 데 실패했을 때의 처리
    function showError(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                alert("위치 정보 사용이 허용되지 않았습니다.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("위치 정보를 사용할 수 없습니다.");
                break;
            case error.TIMEOUT:
                alert("위치 정보를 가져오는 데 시간이 초과되었습니다.");
                break;
            case error.UNKNOWN_ERROR:
                alert("알 수 없는 오류가 발생했습니다.");
                break;
        }
    }
 
    // 위치 정보 요청
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showMap, showError);
        } else {
            alert("이 브라우저에서는 Geolocation을 지원하지 않습니다.");
        }
    }
 
    // 페이지 로드 시 위치 정보 요청
    window.onload = getLocation;
</script>
 
<!-- Google Maps API 스크립트 추가 -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
 
</body>
</html>
cs