본문 바로가기

개발 지식/API

API :: Geolocation API (구글 맵 API)

 

 

Geolocation
Geolocation API는 navigator.geolocation 객체를 통해 사용할 수 있다

 

 

HTML

    <div class="container">
        <h2>현재 위치 보기</h2>
        <button id="find-me" class="btn btn-primary">내 위치 보기</button>
        <p id="status"></p>
        <p id="status-detail"></p>
        <div id="map"></div>
    </div>

 

 

구글맵 API 키 설정

https://console.cloud.google.com/apis/dashboard?hl=ko&project=groupware-428904

<script async src="https://maps.googleapis.com/maps/api/js?key=####구글맵API 키####"></script>

 

 

JavaScript

function geoFindMe() {
        const status = document.querySelector("#status");
        const statusDetail = document.querySelector("#status-detail");

        function success(position) {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;

            const latitudeFormatted = latitude.toFixed(6);
            const longitudeFormatted = longitude.toFixed(6);

            status.textContent = "현재 위치: 위도 " + latitudeFormatted + "°, 경도 " + longitudeFormatted + "°";

            // Google Maps API 초기화
            const mapDiv = document.getElementById("map");
            const mapOptions = {
                center: { lat: latitude, lng: longitude },
                zoom: 15 // 지도의 확대 수준
            };
            const map = new google.maps.Map(mapDiv, mapOptions);

            // 마커 추가
            const marker = new google.maps.Marker({
                position: { lat: latitude, lng: longitude },
                map: map,
                title: '현재 위치'
            });

            // 위치를 주소로 변환하여 출력
            const geocoder = new google.maps.Geocoder();
            const latlng = { lat: latitude, lng: longitude };

            geocoder.geocode({ 'location': latlng }, function(results, status) {
                if (status === 'OK') {
                    if (results[0]) {
                        statusDetail.textContent = "현재 위치 주소: " + results[0].formatted_address;
                    } else {
                        statusDetail.textContent = "주소를 찾을 수 없습니다.";
                    }
                } else {
                    statusDetail.textContent = "Geocoder 실패: " + status;
                }
            });
        }

        function error() {
            status.textContent = "현재 위치를 가져올 수 없음";
        }

        if (!navigator.geolocation) {
            status.textContent = "브라우저가 위치 정보를 지원하지 않음";
        } else {
            status.textContent = "위치 파악 중…";
            navigator.geolocation.getCurrentPosition(success, error);
        }
    }

    document.getElementById("find-me").addEventListener("click", geoFindMe);

 

 

실행 화면

현재 위치의 위도, 경도

현재 위치의 주소명을 구글 맵으로부터 불러오기

현재 위치의 구글맵 조회

'개발 지식 > API' 카테고리의 다른 글

API :: CLOVA Summary (AI 요약 Service)  (0) 2024.08.27
API :: PDF api 사용하기  (0) 2024.07.07
API :: 공공 API 사용하기 (기상청)  (0) 2024.07.06
API :: 카카오톡 로그인 API  (0) 2024.07.05