구글맵 API 소스 수정 문의

구글맵 API 소스 수정 문의

QA

구글맵 API 소스 수정 문의

본문

구글링과 여기저기 묻고 답하기를 통해 아래와 같은 구글맵API 연동소스를 구현하였습니다.

그런데, 지도에 각 지역의 텍스트가 모두 표시되다보니
중복표시되는 부분이 너무 많아서 보기가 어려워서요.

옵션을 조금 변경해서 적용하려고 합니다.

 

1. 지도에 처음에는 마커만 표시됨

2. 마커에 오버롤하면 텍스트 출력 (label값)

3. 오버롤시 나타난 텍스트(label값)를 클릭하면 url 링크로 이동

 

▣ 구글맵 소스 부분

 

    <title>Google Maps with Marker Click and Custom Info</title>
    <style>
        /* 지도 크기 설정 */
        #map {
            height: 500px;
            width: 100%;
        }
    </style>

    <h3>Google Maps with Marker Click and Custom Info</h3>
    <div id="map"></div>

    <script>
        // 구글 맵 초기화 함수
        function initMap() {
            // 맵의 초기 중심 좌표와 줌 설정
            const mapOptions = {
                center: { lat: 37.5665, lng: 126.9780 }, // 서울 좌표
                zoom: 10
            };

            // 맵 객체 생성
            const map = new google.maps.Map(document.getElementById("map"), mapOptions);

            // 마커 데이터 배열
            const malls = [
                { label: "Austria", name: "Austria", lat: 47.5162, lng: 14.5501, url: "austria.html" },
                { label: "Australia", name: "Australia", lat: -25.2744, lng: 133.7751, url: "Australia.html" },
                { label: "Bangkok", name: "Bangkok", lat: 13.7563, lng: 100.5018, url: "Bangkok.html" },
                { label: "Canada", name: "Canada", lat: 56.1304, lng: -106.3468, url: "Canada.html" },
                { label: "China", name: "China", lat: 35.8617, lng: 104.1954, url: "China.html" }
            ];

            // 맵 경계 설정
            const bounds = new google.maps.LatLngBounds();

            // 각 마커를 생성하고 이벤트 리스너 추가
            malls.forEach(({ label, name, lat, lng, url, highlight }) => {
                const marker = new google.maps.Marker({
                    position: { lat, lng },
                    label,
                    map,
                    icon: highlight ? "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" : undefined
                });

                // 맵 경계 확장
                bounds.extend(marker.position);

                // 마커 클릭 이벤트
                marker.addListener("click", () => {
                    window.location.href = url;
                });
            });

            // 모든 마커를 포함하도록 맵 경계 설정
            map.fitBounds(bounds);
        }

        // 구글 맵 API 스크립트 로드
        // 반드시 실제 API 키로 대체해야 합니다.
        function loadScript() {
            const script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=AIzaSyDvTBfuE6Nb8P6uPnt0FL66jsF3lEurzIs&callback=initMap`;
            script.defer = true;
            script.async = true;
            document.head.appendChild(script);
        }

        // 스크립트 로드 함수 호출
        window.onload = loadScript;
    </script>

 

===========================================

 

위의 소스를 아래와 같이 변경 적용하려면 어떻게 수정하면 될까요?

 

1. 지도에 처음에는 마커만 표시됨

2. 마커에 오버롤하면 텍스트 출력 (label값)

3. 오버롤시 나타난 텍스트(label값)를 클릭하면 url 링크로 이동

 

도움 부탁 드립니다. 감사합니다.

이 질문에 댓글 쓰기 :

답변 1

클로드에 물어보니 아래와 같이 답 주네요.

 



            // 각 마커를 생성하고 이벤트 리스너 추가
            malls.forEach(({ label, name, lat, lng, url, highlight }) => {
                const marker = new google.maps.Marker({
                    position: { lat, lng },
                    label,
                    map,
                    icon: highlight ? "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" : undefined
                });
                // 맵 경계 확장
                bounds.extend(marker.position);
                
                const infowindow = new google.maps.InfoWindow({
                    content: `<div><strong>${label}</strong><br><a href="${url}" target="_blank">자세히 보기</a></div>`
                });
                marker.addListener('mouseover', function() {
                    infowindow.open(map, marker);
                });
                
                /*
                marker.addListener('mouseout', function() {
                    infowindow.close();
                });
                */
                marker.addListener('click', function() {
                    window.open(url, '_blank');
                });
            });
 
답변을 작성하시기 전에 로그인 해주세요.
전체 0
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT