지도 경계
공식 예제 대응네이버 공식 예제 보기 ↗
현재 지도 경계를 Rectangle로 표시하고 특정 위치로 이동합니다.
코드 접기코드 보기
import { useRef, useState } from 'react';
import {
NavermapsProvider,
Container as MapDiv,
NaverMap,
Rectangle,
useNavermaps,
} from 'react-naver-maps';
const buttonStyle = {
backgroundColor: '#fff',
border: 'solid 1px #333',
outline: '0 none',
borderRadius: '5px',
boxShadow: '2px 2px 1px 1px rgba(0, 0, 0, 0.5)',
fontSize: '16px',
lineHeight: '1.15',
padding: '1px 6px',
margin: '0 5px 5px 0',
cursor: 'pointer' as const,
};
function MapBoundsMapContent() {
const navermaps = useNavermaps();
const mapRef = useRef<naver.maps.Map>(null);
const [bounds, setBounds] = useState<naver.maps.LatLngBounds | null>(null);
// SDK 객체는 렌더마다 만들지 않고 한 번만 만듭니다.
const [dokdoBounds] = useState(
() =>
new navermaps.LatLngBounds(
new navermaps.LatLng(37.2380651, 131.8562652),
new navermaps.LatLng(37.2444436, 131.8786475),
),
);
return (
<>
<NaverMap
ref={mapRef}
defaultCenter={{ lat: 37.5666805, lng: 126.9784147 }}
defaultZoom={10}
defaultMapTypeId={navermaps.MapTypeId.NORMAL}
onInit={() => {
if (mapRef.current)
setBounds(mapRef.current.getBounds() as naver.maps.LatLngBounds);
}}
onBoundsChanged={(newBounds) => {
window.setTimeout(
() => setBounds(newBounds as naver.maps.LatLngBounds),
500,
);
}}
>
{bounds && (
<Rectangle
bounds={bounds}
strokeOpacity={0}
strokeWeight={0}
fillOpacity={0.2}
fillColor="#f00"
/>
)}
</NaverMap>
<div
style={{
position: 'absolute',
top: 0,
left: 0,
zIndex: 1000,
padding: '5px',
}}
>
<button
style={buttonStyle}
onClick={() => mapRef.current?.fitBounds(dokdoBounds)}
>
독도로 이동하기
</button>
</div>
</>
);
}
function MapBoundsMap() {
return (
<MapDiv style={{ width: '100%', height: '600px' }}>
<MapBoundsMapContent />
</MapDiv>
);
}
export default function MapBoundsExample() {
return (
<NavermapsProvider ncpKeyId="aluya4ff04">
<MapBoundsMap />
</NavermapsProvider>
);
}설명
onBoundsChanged로 받은 경계를 0.5초 뒤 state에 저장하고 Rectangle의 bounds로 전달합니다. 처음 경계는 onInit에서 getBounds()로 가져옵니다. 버튼에서는 ref로 받은 지도의 fitBounds()를 호출합니다. 독도 경계 객체는 렌더마다 만들지 않도록 useState 초기화 함수로 한 번만 만듭니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
new naver.maps.Rectangle({ map, bounds })를 만들고 setBounds()로 변경 | <Rectangle bounds>에 state 전달 |
Event.addListener(map, 'bounds_changed') | onBoundsChanged prop |
지도를 만든 직후 map.getBounds()로 처음 경계 읽기 | onInit에서 getBounds()로 state 설정 |
jQuery 클릭 핸들러에서 map.fitBounds() 호출 | 버튼 onClick에서 ref로 받은 지도의 fitBounds() 호출 |