파노라마 크기 변경하기
공식 예제 대응네이버 공식 예제 보기 ↗
버튼으로 거리뷰 크기를 부드럽게 바꿉니다.
코드 접기코드 보기
import { useEffect, useRef, useState } from 'react';
import { NavermapsProvider, Container as PanoDiv } from 'react-naver-maps';
import { Panorama } from 'react-naver-maps/panorama';
type Size = { width: number; height: number };
const SIZES: Size[] = [
{ width: 200, height: 200 },
{ width: 400, height: 300 },
{ width: 600, height: 400 },
{ width: 800, height: 500 },
];
/** 크기를 500ms 동안 부드럽게 바꿉니다. 공식 예제의 jQuery animate에 해당합니다. */
function useAnimatedSize(target: Size): Size {
const [size, setSize] = useState(target);
const sizeRef = useRef(size);
sizeRef.current = size;
useEffect(() => {
const from = sizeRef.current;
const start = performance.now();
let frame = requestAnimationFrame(function step(now) {
const t = Math.min((now - start) / 500, 1);
setSize({
width: Math.round(from.width + (target.width - from.width) * t),
height: Math.round(from.height + (target.height - from.height) * t),
});
if (t < 1) frame = requestAnimationFrame(step);
});
return () => cancelAnimationFrame(frame);
}, [target]);
return size;
}
function PanoramaResize() {
const [target, setTarget] = useState(SIZES[1]);
const size = useAnimatedSize(target);
return (
<>
<PanoDiv
style={{
position: 'relative',
width: size.width,
height: size.height,
maxWidth: '100%',
// 화면이 거리뷰보다 좁으면 넘치지 않고 잘리게 합니다.
overflow: 'hidden',
}}
>
{/* Container 크기가 바뀌어도 거리뷰에 반영되지 않아 size도 함께 변경합니다. */}
<Panorama
position={{ lat: 37.3599605, lng: 127.1058814 }}
pov={{ pan: -135, tilt: 29, fov: 100 }}
size={size}
/>
{/* 크기가 바뀔 때 거리뷰 중심을 보는 십자선 */}
<div
style={{
position: 'absolute',
top: 0,
left: '50%',
height: '100%',
borderRight: 'solid 1px red',
pointerEvents: 'none',
zIndex: 100,
}}
/>
<div
style={{
position: 'absolute',
top: '50%',
left: 0,
width: '100%',
borderBottom: 'solid 1px red',
pointerEvents: 'none',
zIndex: 100,
}}
/>
</PanoDiv>
<div style={{ marginTop: 5 }}>
{SIZES.map((s) => (
<input
key={s.width}
type="button"
style={{ marginRight: 10 }}
value={`${s.width} x ${s.height}`}
onClick={() => setTarget(s)}
/>
))}
</div>
</>
);
}
export default function PanoramaTutorial2ResizeExample() {
return (
<NavermapsProvider ncpKeyId="aluya4ff04" submodules={['panorama']}>
<PanoramaResize />
</NavermapsProvider>
);
}설명
SDK는 Container가 바뀌어도 거리뷰 크기를 따라가지 않으므로 Container의 크기와 Panorama의 size prop을 같은 state로 함께 바꿉니다. 500ms 보간은 useAnimatedSize가 requestAnimationFrame 마다 state를 갱신해 만듭니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
jQuery animate의 step · progress에서 pano.setSize | requestAnimationFrame으로 500ms 동안 크기 state를 갱신해 Container 크기와 Panorama의 size prop에 전달 |
jQuery css로 가운데 표시(#origin-marker) 옮기기 | 50% 위치에 둔 십자선 div. 크기가 바뀌어도 위치 유지 |
다르게 동작하거나 옮기지 못한 점
- 버튼의 크기는 공식 예제(600 x 600, 400 x 500, 400 x 200)와 다른 네 가지(200 x 200부터 800 x 500)이고, 처음 크기도 공식의 400 x 400 대신 400 x 300입니다.