다수의 마커에 이벤트 핸들러 사용하기
공식 예제 대응네이버 공식 예제 보기 ↗
마커를 클릭하면 해당 마커의 정보 창을 열고 닫습니다.
코드 접기코드 보기
import { useRef, useState } from 'react';
import {
NavermapsProvider,
Container as MapDiv,
NaverMap,
Marker,
InfoWindow,
} from 'react-naver-maps';
const IMG = 'https://navermaps.github.io/maps.js.ncp/docs/img/example';
const X_OFFSET = 29;
const Y_OFFSET = 50;
const spots = Array.from({ length: 27 }, (_, n) => {
const col = n % 9;
const row = Math.floor(n / 9);
const rand = (seed: number) => {
const x = Math.sin(seed * 9301 + 49297) * 233280;
return x - Math.floor(x);
};
return {
key: `${'ABCDEFGHI'[col]}${row}`,
letter: 'ABCDEFGHI'[col],
position: {
lat: 37.2 + 0.32 * rand(n + 1),
lng: 126.83 + 0.55 * rand(n + 101),
},
origin: { x: col * X_OFFSET, y: row * Y_OFFSET },
};
});
type Spot = (typeof spots)[number];
// 마커와 정보 창을 묶고 각 컴포넌트에서 state를 관리합니다.
function SpotMarker({ spot }: { spot: Spot }) {
const [marker, setMarker] = useState<naver.maps.Marker | null>(null);
const [open, setOpen] = useState(false);
return (
<>
<Marker
ref={setMarker}
position={spot.position}
title={spot.key}
zIndex={100}
icon={{
url: `${IMG}/sp_pins_spot_v3.png`,
size: { width: 24, height: 37 },
anchor: { x: 12, y: 37 },
origin: spot.origin,
}}
onClick={() => setOpen((prev) => !prev)}
/>
<InfoWindow
anchor={marker ?? undefined}
open={open && marker !== null}
content={`<div style="width:150px;text-align:center;padding:10px;">The Letter is <b>"${spot.letter}"</b>.</div>`}
// 다른 정보 창이 열려 SDK가 이 창을 닫으면 state도 맞춥니다.
onClose={() => setOpen(false)}
/>
</>
);
}
function MarkerViewportEventsMapContent() {
const mapRef = useRef<naver.maps.Map>(null);
const [bounds, setBounds] = useState<naver.maps.LatLngBounds | null>(null);
const visible = bounds
? spots.filter((spot) => bounds.hasLatLng(spot.position))
: spots;
return (
<NaverMap
ref={mapRef}
defaultCenter={{ lat: 37.3595704, lng: 127.105399 }}
defaultZoom={10}
onIdle={() =>
setBounds(mapRef.current?.getBounds() as naver.maps.LatLngBounds)
}
>
{visible.map((spot) => (
<SpotMarker key={spot.key} spot={spot} />
))}
</NaverMap>
);
}
export default function MarkerViewportEventsExample() {
return (
<NavermapsProvider ncpKeyId="aluya4ff04">
<MapDiv style={{ width: '100%', height: '400px' }}>
<MarkerViewportEventsMapContent />
</MapDiv>
</NavermapsProvider>
);
}설명
영역 필터는 보이는 지도 영역의 마커만 표시하기와 같습니다. 마커 ref는 setMarker로 state에 담아 InfoWindow의 anchor로 넘깁니다. 다른 정보 창이 열려 SDK가 이 창을 닫으면 onClose로 state를 맞춥니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
markers·infoWindows 배열과 getClickHandler(seq) 클로저로 마커마다 핸들러 등록 | 마커 하나와 InfoWindow를 묶은 SpotMarker 컴포넌트에서 open state 관리 |
클릭 핸들러에서 infoWindow.open(map, marker)·close() 호출 | <InfoWindow>의 anchor·open prop |
idle 리스너에서 영역 밖 마커를 setMap(null) | onIdle에서 영역을 state에 담고 영역 안의 마커만 렌더 |
처음 지도 영역 안에서 Math.random()으로 마커 위치 선택 | 미리 정한 고정 좌표 사용(다시 열어도 같은 위치) |