투영법과 타일의 크기를 동적으로 변경하기
공식 예제 대응네이버 공식 예제 보기 ↗
네이버 지도와 OSM 두 지도 유형을 오가며 타일 크기를 바꿉니다.
코드 접기코드 보기
import { useMemo, useRef, useState } from 'react';
import {
NavermapsProvider,
Container as MapDiv,
NaverMap,
Marker,
useNavermaps,
} from 'react-naver-maps';
const TILE_SIZES = [
[64, 64],
[128, 128],
[256, 256],
[512, 512],
[256, 128],
[256, 64],
] as const;
function DynamicMapContent() {
const navermaps = useNavermaps();
const mapRef = useRef<naver.maps.Map>(null);
const [tileSize, setTileSize] = useState<string>('256x256');
// 두 지도 유형을 한 번 만들고 인스턴스로 타일 크기를 바꿉니다.
const { mapTypes, mapTypeList } = useMemo(() => {
const naverNormal = navermaps.NaverStyleMapTypeOptions.getNormalMap();
const osm = new navermaps.ImageMapType({
name: 'OSM',
minZoom: 0,
maxZoom: 19,
tileSize: new navermaps.Size(256, 256),
projection: navermaps.EPSG3857,
repeatX: true,
tileSet: [
'https://a.tile.openstreetmap.org/{z}/{x}/{y}.png',
'https://b.tile.openstreetmap.org/{z}/{x}/{y}.png',
'https://c.tile.openstreetmap.org/{z}/{x}/{y}.png',
],
provider: [
{
title: ' /OpenStreetMap',
link: 'http://www.openstreetmap.org/copyright',
},
],
});
return {
mapTypes: new navermaps.MapTypeRegistry({ naver: naverNormal, osm }),
mapTypeList: [naverNormal, osm],
};
}, [navermaps]);
function changeTileSize(value: string) {
const [width, height] = value.split('x').map(Number);
for (const mapType of mapTypeList) {
const options = mapType.getMapTypeOptions();
options.tileSize = new navermaps.Size(width, height);
mapType.setMapTypeOptions(options);
}
// 효과 없이 타일을 새 크기로 다시 그립니다.
mapRef.current?.refresh(true);
setTileSize(value);
}
return (
<>
<NaverMap
ref={mapRef}
defaultCenter={{ lat: 37.3595704, lng: 127.105399 }}
mapTypes={mapTypes}
defaultMapTypeId="naver"
mapTypeControl
mapTypeControlOptions={{ style: navermaps.MapTypeControlStyle.BUTTON }}
>
<Marker position={{ lat: 37.3595704, lng: 127.105399 }} />
</NaverMap>
<div
style={{
position: 'absolute',
left: 0,
bottom: 0,
zIndex: 1000,
padding: '5px 10px',
backgroundColor: '#fff',
border: 'solid 1px #333',
fontSize: 14,
}}
>
<strong>타일 크기 변경</strong>
<br />
{TILE_SIZES.map(([width, height]) => {
const value = `${width}x${height}`;
return (
<label key={value} style={{ marginRight: 15 }}>
<input
type="radio"
name="tile-size"
value={value}
checked={tileSize === value}
onChange={() => changeTileSize(value)}
/>{' '}
{width} x {height}
</label>
);
})}
</div>
</>
);
}
export default function MapTypesTutorial4DynamicExample() {
return (
<NavermapsProvider ncpKeyId="aluya4ff04">
<MapDiv style={{ width: '100%', height: '600px' }}>
<DynamicMapContent />
</MapDiv>
</NavermapsProvider>
);
}설명
지도 유형 컨트롤(mapTypeControlOptions)로 투영법이 다른 두 유형을 전환합니다.
타일 크기는 선언적 prop이 없어서 지도 유형 인스턴스의 getMapTypeOptions(), setMapTypeOptions()로 바꿉니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
| 두 지도 유형 인스턴스를 스크립트 변수로 들고 있기 | useMemo로 한 번 만들어 레지스트리와 배열(mapTypeList)에 저장 |
| jQuery로 라디오 버튼에 클릭 리스너 붙이기 | 라디오 버튼은 React state(tileSize)로 제어하고 onChange에서 타일 크기 변경 |
map.refresh(true)로 다시 그리기 | ref로 받은 지도의 refresh(true) 호출 |
new naver.maps.Marker를 지도 중심에 만들기 | <Marker position>을 NaverMap의 children으로 렌더링 |