React Naver Maps
136

예제/공식 예제/컨트롤

커스텀 컨트롤

공식 예제 대응네이버 공식 예제 보기 ↗

지도 컨트롤에 직접 만든 버튼을 넣습니다. 버튼을 누르면 NAVER 그린팩토리로 이동합니다. 컨트롤 두 개를 TOP_LEFT와 LEFT_CENTER에 둡니다.

코드 접기코드 보기
import {
  NavermapsProvider,
  Container as MapDiv,
  NaverMap,
  CustomControl,
  useNavermaps,
  useMap,
} from 'react-naver-maps';

const buttonStyle = {
  display: 'inline-block',
  width: 34,
  height: 34,
  margin: 5,
  border: '1px solid rgba(58,70,88,.45)',
  borderRadius: 2,
  background: '#fcfcfd',
  backgroundClip: 'padding-box',
  textAlign: 'center',
  cursor: 'pointer',
} as const;

const iconStyle = {
  display: 'inline-block',
  width: 20,
  height: 20,
  margin: '7px 0 0 0',
  background: 'url(https://ssl.pstatic.net/static/maps/m/spr_trff_v6.png) 0 0',
  backgroundSize: '200px 200px',
  backgroundPosition: '-153px -31px',
} as const;

const GREEN_FACTORY = { lat: 37.3595953, lng: 127.1053971 };
// 공식 예제의 두 번째 컨트롤(map.controls[LEFT_CENTER])이 이동하는 위치입니다. 경도가 조금 다릅니다.
const GREEN_FACTORY_EAST = { lat: 37.3595953, lng: 127.1553971 };

function HomeControl() {
  const navermaps = useNavermaps();
  const map = useMap();

  return (
    <>
      <CustomControl position={navermaps.Position.TOP_LEFT}>
        <button
          type="button"
          aria-label="NAVER 그린팩토리로 이동"
          style={buttonStyle}
          onClick={() => map.setCenter(GREEN_FACTORY)}
        >
          <span style={iconStyle} />
        </button>
      </CustomControl>
      <CustomControl position={navermaps.Position.LEFT_CENTER}>
        <button
          type="button"
          aria-label="NAVER 그린팩토리 동쪽으로 이동"
          style={buttonStyle}
          onClick={() => map.setCenter(GREEN_FACTORY_EAST)}
        >
          <span style={iconStyle} />
        </button>
      </CustomControl>
    </>
  );
}

export default function CustomControlExample() {
  return (
    <NavermapsProvider ncpKeyId="aluya4ff04">
      <MapDiv style={{ width: '100%', height: '600px' }}>
        <NaverMap defaultZoom={13}>
          <HomeControl />
        </NaverMap>
      </MapDiv>
    </NavermapsProvider>
  );
}

설명

CustomControl의 children이 컨트롤 위치(position)에 렌더링됩니다. 일반 React 요소이므로 onClick을 그대로 사용할 수 있습니다. 버튼에서는 useMap()으로 받은 지도의 setCenter()를 호출합니다.

지도가 준비(init)되기 전에 마운트해도 준비된 뒤 붙습니다. SDK의 CustomControl.setMap은 준비 전에는 붙이지 않기 때문입니다.

React로 옮기며 바꾼 점

네이버 공식 예제이 예제
new naver.maps.CustomControl(html, { position })과 setMap(map)<CustomControl position>의 children으로 React 요소 렌더링
jQuery로 만든 요소를 map.controls[position].push()로 추가두 번째 <CustomControl>로 같은 컴포넌트 사용
Event.addDOMListener로 붙이는 click 리스너버튼의 onClick
Event.once(map, 'init') 안에서 컨트롤 생성지도가 준비되기 전에 마운트해도 준비된 뒤 표시
전역 map 변수의 setCenter()useMap()으로 받은 지도의 setCenter()