구글맵 마커에 링크 거는 방법

구글맵 마커에 링크 거는 방법

QA

구글맵 마커에 링크 거는 방법

본문

구글맵 API 를 활용하여, 세계지도에 마커로 지점을 표시하는 작업을 하고 있습니다.

아래 팁을 활용해서, 지도에 마커를 표시하는 것 까지는 성공했습니다.

 

https://www.daleseo.com/google-maps-api/

 

추가하고 싶은 부분은 마커를 클릭하면 열리는 인포창에서 링크를 추가하고 싶습니다.

 

예를들면 위의 팁의 링크에서 보면 코엑스몰을 클릭하면 인포창에서 "코엑스몰" 이라는 텍스트만 보이는데요.

아마도 name 값을 그대로 불러오는 것 같습니다.

 

여기에 [상세정보 보기] 라는 링크를 추가하고, 클릭하면 원하는 URL로 이동되게 하고 싶습니다.

어느 부분을 수정해서 적용해야 할까요?

 

참고로, 아래 부분이 구글맵 마커를 생성하는 JS 소스 부분입니다.

여기에 마커에 링크를 걸 수 있도록 추가하려면 어떻게 해야 할까요?

도움 부탁 드립니다. 

 

window.initMap = function () {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 65.67111111111112, lng: 95.17492654697409 },
    zoom: 100
  });

  const malls = [
    { label: "C", name: "코엑스몰", lat: 65.67111111111112, lng: 95.17492654697409 },
    { label: "G", name: "고투몰", lat: 37.5062379, lng: 127.0050378 },
    { label: "D", name: "동대문시장", lat: 37.566596, lng: 127.007702 },
    { label: "I", name: "IFC몰", lat: 37.5251644, lng: 126.9255491 },
    { label: "L", name: "롯데월드타워몰", lat: 37.5125585, lng: 127.1025353 },
    { label: "M", name: "명동지하상가", lat: 37.563692, lng: 126.9822107 },
    { label: "T", name: "타임스퀘어", lat: 37.5173108, lng: 126.9033793 }
  ];

  const bounds = new google.maps.LatLngBounds();
  const infoWindow = new google.maps.InfoWindow();

  malls.forEach(({ label, name, lat, lng }) => {
    const marker = new google.maps.Marker({
      position: { lat, lng },
      label,
      map
    });
    bounds.extend(marker.position);

    marker.addListener("click", () => {
      map.panTo(marker.position);
      infoWindow.setContent(name);
      infoWindow.open({
        anchor: marker,
        map
      });
    });
  });

  map.fitBounds(bounds);
};
 

 

이 질문에 댓글 쓰기 :

답변 4

아래의 내용을 참고해보시겠어요..

 

 

<!DOCTYPE html>
<html>
<head>
    <title>Google Maps with InfoWindow and Links</title>
    <style>
        /* 지도 크기 설정 */
        #map {
            height: 500px;
            width: 100%;
        }
    </style>
</head>
<body>
    <h3>Google Maps with InfoWindow and Links</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: "C", name: "코엑스몰", lat: 37.512585, lng: 127.059537, url: "https://www.coexmall.com" },
                { label: "G", name: "고투몰", lat: 37.5062379, lng: 127.0050378, url: "https://www.gotomall.co.kr" },
                { label: "D", name: "동대문시장", lat: 37.566596, lng: 127.007702, url: "https://www.ddm-mall.com" },
                { label: "I", name: "IFC몰", lat: 37.5251644, lng: 126.9255491, url: "https://www.ifcseoul.com" },
                { label: "L", name: "롯데월드타워몰", lat: 37.5125585, lng: 127.1025353, url: "https://www.lwt.co.kr" },
                { label: "M", name: "명동지하상가", lat: 37.563692, lng: 126.9822107, url: "https://www.mymdong.com" },
                { label: "T", name: "타임스퀘어", lat: 37.5173108, lng: 126.9033793, url: "https://www.timessquare.co.kr" }
            ];

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

            // 각 마커를 생성하고 이벤트 리스너 추가
            malls.forEach(({ label, name, lat, lng, url }) => {
                const marker = new google.maps.Marker({
                    position: { lat, lng },
                    label,
                    map
                });

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

                // 마커 클릭 이벤트
                marker.addListener("click", () => {
                    map.panTo(marker.position);
                    const content = `
                        <div>
                            <h3>${name}</h3>
                            <a href="${url}" target="_blank">상세정보 보기</a>
                        </div>
                    `;
                    infoWindow.setContent(content);
                    infoWindow.open(map, marker);
                });
            });

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

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

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

 

 

상세한 답변 정말 감사 드립니다.  덕분에 잘 해결했습니다.
추가로 질문 드리면, 아래 내용들도 적용이 가능한 방법이 있을까요?
1) 마커 클릭시 인포창 없이 바로 해당 지점에 대한 설명 페이지(링크주소)로 이동 되도록
→ 상단에 지도는 유지하고, 아래에 해당지점의 설명 내용이 있는 페이지를 각 지점별로 만들어서 링크하려고 합니다.
2) 각 지점 설명페이지에 보여지는 지도에서 설명중인 지점의 마커만 다른 색으로 표시되게 할 수 있을까요?

아래의 코드를 참고해 보시겠어요..

 

 

 

<!DOCTYPE html>
<html>
<head>
    <title>Google Maps with Marker Click and Custom Info</title>
    <style>
        /* 지도 크기 설정 */
        #map {
            height: 500px;
            width: 100%;
        }
    </style>
</head>
<body>
    <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: "C", name: "코엑스몰", lat: 37.512585, lng: 127.059537, url: "coex.html" },
                { label: "G", name: "고투몰", lat: 37.5062379, lng: 127.0050378, url: "gotomall.html" },
                { label: "D", name: "동대문시장", lat: 37.566596, lng: 127.007702, url: "dongdaemun.html" },
                { label: "I", name: "IFC몰", lat: 37.5251644, lng: 126.9255491, url: "ifc.html" },
                { label: "L", name: "롯데월드타워몰", lat: 37.5125585, lng: 127.1025353, url: "lotteworld.html" },
                { label: "M", name: "명동지하상가", lat: 37.563692, lng: 126.9822107, url: "myungdong.html" },
                { label: "T", name: "타임스퀘어", lat: 37.5173108, lng: 126.9033793, url: "timesquare.html" }
            ];

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

            // 각 마커를 생성하고 이벤트 리스너 추가
            malls.forEach(({ label, name, lat, lng, url }) => {
                const marker = new google.maps.Marker({
                    position: { lat, lng },
                    label,
                    map
                });

                // 맵 경계 확장
                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=YOUR_API_KEY&callback=initMap`;
            script.defer = true;
            script.async = true;
            document.head.appendChild(script);
        }

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

 

 

 

- 특정페이지 마커 강조

 

const specialMarker = new google.maps.Marker({
    position: { lat: 37.512585, lng: 127.059537 }, // 코엑스몰 좌표
    label: "C",
    icon: {
        url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" // 파란색 아이콘 사용
    },
    map
});
 

 

 

 

네~ 너무 감사드리고요. 질문이 많아서 죄송합니다. 위의 소스로 적용하니까 바로 링크로 연결되는 부분은 잘 됩니다. 그런데 "특정페이지 마커 강조" 소스를 넣으면 링크가 작동을 안하는 현상이 있습니다.  기존 스크립트 부분에 추가해서 넣으면 파란색 아이콘은 보이는데, 링크만 안되고요, 별도로 스크립트 부분을 따로 추가해서 넣으면 색상도 적용이 안되네요.
마커색 변경 부분을어느 부분에 넣어야 할까요?

아래의 코드를 한번 참고해 보시겠어요..

 

 

<!DOCTYPE html>
<html>
<head>
    <title>Google Maps with Marker Click and Custom Info</title>
    <style>
        /* 지도 크기 설정 */
        #map {
            height: 500px;
            width: 100%;
        }
    </style>
</head>
<body>
    <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: "C", name: "코엑스몰", lat: 37.512585, lng: 127.059537, url: "coex.html", highlight: true },
                { label: "G", name: "고투몰", lat: 37.5062379, lng: 127.0050378, url: "gotomall.html" },
                { label: "D", name: "동대문시장", lat: 37.566596, lng: 127.007702, url: "dongdaemun.html" },
                { label: "I", name: "IFC몰", lat: 37.5251644, lng: 126.9255491, url: "ifc.html" },
                { label: "L", name: "롯데월드타워몰", lat: 37.5125585, lng: 127.1025353, url: "lotteworld.html" },
                { label: "M", name: "명동지하상가", lat: 37.563692, lng: 126.9822107, url: "myungdong.html" },
                { label: "T", name: "타임스퀘어", lat: 37.5173108, lng: 126.9033793, url: "timesquare.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=YOUR_API_KEY&callback=initMap`;
            script.defer = true;
            script.async = true;
            document.head.appendChild(script);
        }

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

 

 

답변을 작성하시기 전에 로그인 해주세요.
전체 0
QA 내용 검색

회원로그인

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