지도 좌표 경계 확인하기

네이버지도 공식 튜토리얼 지도 유형 설정하기의 구현 예시입니다.

import { useState, useEffect, useRef, useLayoutEffect } from 'react'
import { Container as MapDiv, NaverMap, useNavermaps, Rectangle, useMap } from 'react-naver-maps'

const buttonStyle = {
  position: 'absolute',
  top: 10,
  left: 10,
  zIndex: 1000,
  backgroundColor: '#fff',
  border: 'solid 1px #333',
  outline: '0 none',
  borderRadius: '5px',
  boxShadow: '2px 2px 1px 1px rgba(0, 0, 0, 0.5)',
  margin: '0 5px 5px 0',
}

function MyMap() {
  const navermaps = useNavermaps()
  const center = new navermaps.LatLng(37.5666805, 126.9784147)
  const dokdo = new navermaps.LatLngBounds(
    new navermaps.LatLng(37.2380651, 131.8562652),
    new navermaps.LatLng(37.2444436, 131.8786475),
  )

  const [map, setMap] = useState(null)
  const [rect, setRect] = useState(null)

  // map과 rect가 처음 mount되었을 때에만 동작합니다.
  useLayoutEffect(() => {
    if (map && rect) {
      rect.setBounds(map.getBounds())
    }
  }, [map, rect])

  return (
    <NaverMap
      ref={setMap}
      // uncontrolled KVOs
      defaultCenter={center}
      defaultZoom={10}
      defaultMapTypeId={navermaps.MapTypeId.NORMAL}
      // event handler
      onBoundsChanged={(bounds) => {
        if (rect) {
          window.setTimeout(function () {
            rect.setBounds(bounds)
          }, 500)
        }
      }}
    >
      <Rectangle
        ref={setRect}
        strokeOpacity={0}
        strokeWeight={0}
        fillOpacity={0.2}
        fillColor={'#f00'}
      />
      <button
        style={buttonStyle}
        onClick={(e) => {
          e.preventDefault()
          if (map) {
            map.fitBounds(dokdo)
          }
        }}
      >
        독도로 이동하기
      </button>
    </NaverMap>
  )
}

<MapDiv
  style={{
    position: 'relative',
    width: '100%',
    height: '600px',
  }}
>
  <MyMap />
</MapDiv>
React Naver Maps