본문으로 건너뛰기

useMap

useMapMapProvider 아래에서 현재 지도 인스턴스와 등록된 지도들을 가져오는 훅입니다.

기본 사용법

import { Map, MapProvider, useMap } from "@rousen/react-naver-maps";

function ZoomInButton() {
const { current } = useMap();
return (
<button onClick={() => current?.setZoom((current.getZoom() ?? 10) + 1)}>
줌 인
</button>
);
}

function App() {
return (
<MapProvider>
<Map ncpKeyId="your-ncp-key-id" />
<ZoomInButton />
</MapProvider>
);
}

반환값

useMap은 아래와 같은 형태의 객체를 반환합니다.

type MapCollection = {
[id: string]: naver.maps.Map | undefined;
current?: naver.maps.Map;
};
  • current: 현재 렌더링 중인 Map 인스턴스
  • [id]: Map 컴포넌트에 지정한 id로 접근 가능한 인스턴스

동작 노트

  • useMapMapProvider 내부에서만 동작합니다.
  • current는 가장 가까운 Map 컴포넌트의 컨텍스트를 사용합니다.
  • id를 지정하지 않으면 기본 키는 "default"입니다.

예제

id로 특정 Map 제어

import { Map, MapProvider, useMap } from "@rousen/react-naver-maps";

function CenterControls() {
const maps = useMap();

const moveLeft = () => {
maps.left?.setCenter({ x: 127.0276, y: 37.4979 });
};

return <button onClick={moveLeft}>왼쪽 지도 이동</button>;
}

function App() {
return (
<MapProvider>
<Map id="left" ncpKeyId="your-ncp-key-id" />
<Map id="right" ncpKeyId="your-ncp-key-id" />
<CenterControls />
</MapProvider>
);
}