웹 개발

카카오 지도 api 활용 - 지도 marker, infowindow

s2h15 2023. 10. 23. 12:51
728x90

지도 api를 활용하여 데이터베이스의 위도 경도 등을 

 

1. infowindow 내용이 마커를 삭제해도 남아있음

var infowindow; 로 선언 한 후
infowindow = new kakao.maps.InfoWindow({
                content: content,
                removable: true
            });
코드를 creatMarker안으로 위치를 변경하는 것을 통해 해결
 

2.  마커가 하나만 남아있음

- address=city ;와 createMarker(lat, lng, content); 위치 변경으로 해결

<!DOCTYPE html>
<html lang="en">
    
    <head >
        <meta charset="utf-8">
        <title>지도와 마커 표시하기</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</head>

<style>
    /* Add your CSS styles here */
    body {
      position: relative; 
   }
    .map-design {
        width: 100%;
        height: 450px;
        right: 0;
        margin-top: 0rem;
    }

    .info-box {
        padding: 10px;
        margin: 5px;
        width: 250px;
        height: 150px;
        font-size: 12px;
    }

    .asidebar {
        background-color: rgb(158, 212, 248);
        position: fixed;
        margin-top: 0rem;
        bottom: 0;
        float: left;
        transition: 0.4s ease;
        color: #202020;
        height: 100%;
        z-index: 99;
    }

    .ininfo {
        background-color: white;
        padding: 10px;
        margin: 5px;
        width: 250px;
        height: 150px;
        font-size: 12px;
    }
</style>

<body>
    <div id="map" class="map-design"></div>
    
        

    <div id="info-box"></div>

    <input type="checkbox" id="areacheck1" onchange="handleCheckboxChange('북구', this.checked)">북구
    <input type="checkbox" id="areacheck2" onchange="handleCheckboxChange('광산구', this.checked)">광산구
    <input type="checkbox" id="areacheck3" onchange="handleCheckboxChange('서구', this.checked)">서구
    <input type="checkbox" id="areacheck4" onchange="handleCheckboxChange('동구', this.checked)">동구
    <input type="checkbox" id="areacheck5" onchange="handleCheckboxChange('남구', this.checked)">남구
    <input type="checkbox" id="areacheck6" onchange="handleCheckboxChange2('전체', this.checked)">전체
    
    
    
    
    <script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=f6654953f7f2de9be8090793a3c14e09&libraries=services"></script>
    <script>
        let map;
        let markers = [];
        var content;
        var infowindow;
        var address;
        
        navigator.geolocation.getCurrentPosition(function (position) {
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            createMap(lat, lng);
        });

        function createMap(lat, lng) {
            const container = document.getElementById('map');
            const options = {
                center: new kakao.maps.LatLng(lat, lng),
                level: 9
            };
            map = new kakao.maps.Map(container, options);
        }
        
        
        function getData(city) {
            fetch('/tetest/data')
            .then(response => response.json())
            .then(data => {
                data.forEach(v => {
                    const lat = v.latitude;
                    const lng = v.longitude;
                    const cityData = v.city;
                    
                    if (cityData === city) {
                        var content = `<div class="info-box"> 충전소 위치: ${v.name} <br> 주소: ${v.address} <br> 운영기관: ${v.company} <br> 이용가능시간: ${v.tim}</div>`;
                        address=city;
                        createMarker(lat, lng, content);
                    }
                        
                    });
                })
                .catch(error => console.log(error));
        }

        function createMarker(lat, lng, content) {
            const markerPosition = new kakao.maps.LatLng(lat, lng);
            var imageSrc = 'https://cdn-icons-png.flaticon.com/512/7512/7512521.png', // 마커이미지의 주소입니다    
                imageSize = new kakao.maps.Size(50, 52), // 마커이미지의 크기입니다
                imageOption = {offset: new kakao.maps.Point(27, 69)}; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.
                // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
                var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption);
            const marker = new kakao.maps.Marker({
                position: markerPosition,
                image: markerImage
            });
            
            infowindow = new kakao.maps.InfoWindow({
                content: content,
                removable: true
            });
           
            
            kakao.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
                map.panTo(markerPosition);
            });
            const mark = {
                marker: marker,
                add: address
            }

            markers.push(mark);
            marker.setMap(map);
        }
        
        
        function removeInfo(){

            infowindow.close();
        }

        function removeMarkers(city) {
            markers.forEach(mark=> {
                const marker = mark.marker;
                if(mark.add === city){
                    marker.setMap(null); // 지도에서 제거
                }
            });
            // markers = markers.filter(marker => marker.city !== city);
            
        }

       

        function handleCheckboxChange(city, checked) {
            if (checked) {
                getData(city);
            } else {
                removeInfo();
                removeMarkers(city);
                }
            }
        
        function handleCheckboxChange2(city, checked) {
            if (checked) {
                getData('북구');
                getData('광산구');
                getData('동구');
                getData('남구');
                getData('서구');
            } else {
                removeInfo();
                removeMarkers('북구');
                removeMarkers('광산구');
                removeMarkers('동구');
                removeMarkers('남구');
                removeMarkers('서구');
            }
        }
        
    </script>

</body>

</html>

3. 알고보니 content내용이 마커에 따라 달라지지 않고 북구/서구의 한가지 값만 나왔다

-updateInfoBox 라는 함수를 따로 만들어 infowindow click addListener에 추가해주었다

function updateInfoBox(city){
            const inforBox = document.getElementById('information-content');

             fetch('/getCityInfo?city=' + city)
        .then(response => response.json())
        .then(data => {
            infoBox.innerHTML = `
                <p><strong>충전소:</strong> ${data.name}</p>
                <p><strong>주소:</strong> ${data.address}</p>
                <p><strong>운영기관:</strong> ${data.company}</p>
                <p><strong>충전기타입:</strong> ${data.chargerType}</p>
            `;
        })
        .catch(error => console.log(error));
        }

 

 

 

728x90