본문 바로가기
개발

JavaScript에서 카카오맵 리사이징하는 방법

by 농담곰이 2023. 5. 8.
반응형

카카오맵을 JavaScript로 사용하고 있다면, 카카오맵의 크기를 동적으로 조정하고 리사이징하는 방법이 있습니다. 다음은 간단한 예제 코드입니다.

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Kakao Map Resizing</title>
  <style>
    #map {
      width: 100%;
      height: 300px;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <button id="resizeButton">Resize Map</button>
  <script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=YOUR_APP_KEY"></script>
  <script>
    const container = document.getElementById('map');
    const options = {
      center: new kakao.maps.LatLng(37.506502, 127.053617),
      level: 3
    };
    const map = new kakao.maps.Map(container, options);

    const resizeButton = document.getElementById('resizeButton');
    resizeButton.addEventListener('click', () => {
      const newHeight = Math.floor(Math.random() * 300) + 200;
      container.style.height = `${newHeight}px`;
      kakao.maps.event.trigger(map, 'resize');
    });
  </script>
</body>
</html>
```

위의 코드에서 `container` 변수는 맵을 담을 `div` 요소를 가져옵니다. `options` 변수는 맵의 초기 위치와 줌 레벨을 설정합니다. `map` 변수는 맵 객체를 만들어 `container` 요소에 연결합니다.

리사이징을 위해 버튼을 만들고 클릭 이벤트를 등록합니다. 클릭 이벤트에서는 `container` 요소의 높이를 무작위로 변경하고, 맵의 크기를 조정합니다. 이때 `kakao.maps.event.trigger(map, 'resize')`를 사용하여 맵 객체에 리사이징 이벤트를 전달합니다.


위의 코드에서는 높이를 변경하고 있지만, 가로 크기를 변경하려면 `width` 속성을 조정하면 됩니다. 또한, 맵 객체의 크기를 조정하려면 `resize` 이벤트를 수동으로 트리거해야 하며, 이를 위해 `kakao.maps.event.trigger()` 메서드를 사용합니다.

반응형

댓글