[트러블슈팅] 카카오맵 api 불러올때 지도 재범위 설정

김동하·2024년 2월 16일
0

레퍼런스

지도 범위 재설정 하기
지도 범위를 재설정합니다. 어떤 좌표나 마커들이 지도에 모두 보여야 할 때 좌표들의 정보를 갖는 LatLngBounds를 사용하여 좌표들이 모두 보이게 지도의 중심좌표와 레벨을 재설정 할 수 있습니다.


var map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
 
// 버튼을 클릭하면 아래 배열의 좌표들이 모두 보이게 지도 범위를 재설정합니다 
var points = [
    new kakao.maps.LatLng(33.452278, 126.567803),
   
];

// 지도를 재설정할 범위정보를 가지고 있을 LatLngBounds 객체를 생성합니다
var bounds = new kakao.maps.LatLngBounds();    

var i, marker;
for (i = 0; i < points.length; i++) {
    // 배열의 좌표들이 잘 보이게 마커를 지도에 추가합니다
    marker =     new kakao.maps.Marker({ position : points[i] });
    marker.setMap(map);
    
    // LatLngBounds 객체에 좌표를 추가합니다
    bounds.extend(points[i]);
}

function setBounds() {
    // LatLngBounds 객체에 추가된 좌표들을 기준으로 지도의 범위를 재설정합니다
    // 이때 지도의 중심좌표와 레벨이 변경될 수 있습니다
    map.setBounds(bounds);
}

적용

문제점: 중심에서 벗어남 고쳐야함

// bounds 선언
var map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
        // 지도를 재설정할 범위정보를 가지고 있을 LatLngBounds 객체를 생성합니다
        var bounds = new kakao.maps.LatLngBounds();
        function setBounds() {
            // LatLngBounds 객체에 추가된 좌표들을 기준으로 지도의 범위를 재설정합니다
            // 이때 지도의 중심좌표와 레벨이 변경될 수 있습니다
            map.setBounds(bounds);
        }

1번째 시도

console.log(clickPosition);

marker 찍는 함수에다가
bounds.extend(clickPosition); 넣어보기

function addSelectedMarker({la, ma}, index) {

                marker = new kakao.maps.Marker({
                    position: new kakao.maps.LatLng(la, ma), // 마커의 위치
                    image: markerImage
                });
            
            marker.setMap(map)

            var clickPosition = new kakao.maps.LatLng(la, ma)
            // 검색된 장소 위치를 기준으로 지도 범위를 재설정하기위해
            // LatLngBounds 객체에 좌표를 추가합니다
            console.log(clickPosition);
            bounds.extend(clickPosition);
}

실패!!

2번째

console.log(laMas[1].la);

bounds.extend(new kakao.maps.LatLng(laMas[0])); 이거 넣어도 중심 안옮겨짐

const laMas = JSON.parse(/*[[${laMas}]]*/ []);

        laMas.forEach((lama, index) => {
            addSelectedMarker(lama, index);
            // 검색된 장소 위치를 기준으로 지도 범위를 재설정하기위해
            // LatLngBounds 객체에 좌표를 추가합니다
            console.log(laMas[1]);

            bounds.extend(new kakao.maps.LatLng(laMas[0]));
            // bounds.extend(new window.kakao.maps.LatLng(laMas[1]));
        })

도 안됌.

3번째

스트링말고 double 로 해보기
오류뜸

4번째 _해결


setBounds 함수 다 버림.
처음 mapOption에서 center 에 바로 걍 넣음
chatGPT한테 자바스크립트에서 자료형어케바꾸냐고 물어봄 => parseFloat 쓰라함.
=>> 오류lamas가 선언이 안되어있음.
===> lamas 변수선은 위로 올림 해결~~


const laMas = JSON.parse(/*[[${laMas}]]*/ []);
        var mapContainer = document.getElementById('map'), // 지도를 표시할 div
            mapOption = {
                //지도의 중심좌표
                center: new kakao.maps.LatLng(parseFloat(laMas[0].la),parseFloat(laMas[0].ma)),

                level: 7 // 지도의 확대 레벨
            };

0개의 댓글