데이터 레이어 SVG 패턴 적용하기
공식 예제 대응네이버 공식 예제 보기 ↗
지역마다 SVG 패턴으로 채웁니다.
코드 접기코드 보기
import { useMemo, useState } from 'react';
import {
NavermapsProvider,
Container as MapDiv,
NaverMap,
GeoJson,
useMap,
} from 'react-naver-maps';
import { useJsonAll } from '../samples/remote-data';
const REGION_PATHS = Array.from(
{ length: 17 },
(_, i) => `data/region${String(i + 1).padStart(2, '0')}.json`,
);
// 공식 예제는 18개의 SVG 패턴을 사용합니다. 여기서는 같은 방식으로 직접 만든 패턴 6개를 사용합니다.
const PATTERNS: Record<string, React.ReactNode> = {
stripes: (
<>
<rect width="8" height="8" fill="#fff" />
<path d="M0 0L8 8" stroke="#7f5bd5" strokeWidth="2" />
</>
),
dots: (
<>
<rect width="10" height="10" fill="#fff" />
<circle cx="5" cy="5" r="2" fill="#ec3d77" />
</>
),
grid: (
<>
<rect width="10" height="10" fill="#fff" />
<path d="M0 0H10M0 0V10" stroke="#04a8f4" strokeWidth="1" />
</>
),
waves: (
<>
<rect width="20" height="10" fill="#fff" />
<path
d="M0 5Q5 0 10 5T20 5"
fill="none"
stroke="#f2b01e"
strokeWidth="1.5"
/>
</>
),
checks: (
<>
<rect width="12" height="12" fill="#fff" />
<rect width="6" height="6" fill="#03c75a" />
<rect x="6" y="6" width="6" height="6" fill="#03c75a" />
</>
),
triangles: (
<>
<rect width="12" height="12" fill="#fff" />
<path d="M0 12L6 0L12 12Z" fill="#ff8a65" />
</>
),
};
const PATTERN_IDS = Object.keys(PATTERNS);
const PATTERN_SIZE: Record<string, [number, number]> = {
stripes: [8, 8],
dots: [10, 10],
grid: [10, 10],
waves: [20, 10],
checks: [12, 12],
triangles: [12, 12],
};
// 지역 이름으로 패턴을 정해 렌더마다 바뀌지 않게 합니다.
const patternOf = (name: string) =>
`region-${PATTERN_IDS[[...name].reduce((s, c) => s + c.charCodeAt(0), 0) % PATTERN_IDS.length]}`;
const patternStyle = (feature: naver.maps.Feature) => {
const focus = feature.getProperty('focus');
return {
fillColor: `url(#${patternOf(feature.getProperty('area1'))})`,
fillOpacity: focus ? 0.01 : 0.8,
strokeColor: focus ? '#04A8F4' : '#7F5BD5',
strokeWeight: focus ? 4 : 2,
strokeOpacity: focus ? 1 : 0.4,
};
};
function PatternDefs() {
return (
<svg
width="0"
height="0"
style={{ position: 'absolute' }}
aria-hidden="true"
>
<defs>
{PATTERN_IDS.map((id) => (
<pattern
key={id}
id={`region-${id}`}
patternUnits="userSpaceOnUse"
width={PATTERN_SIZE[id][0]}
height={PATTERN_SIZE[id][1]}
patternTransform="scale(2)"
>
{PATTERNS[id]}
</pattern>
))}
</defs>
</svg>
);
}
type Tooltip = { x: number; y: number; text: string };
function Regions({
onTooltip,
}: {
onTooltip: (tooltip: Tooltip | null) => void;
}) {
const map = useMap();
const files = useJsonAll<naver.maps.GeoJSON & { features: unknown[] }>(
REGION_PATHS,
);
const regions = useMemo(
() =>
files && {
type: 'FeatureCollection' as const,
features: files.flatMap((f) => f.features),
},
[files],
);
if (!regions) return null;
return (
<GeoJson
data={regions as unknown as naver.maps.GeoJSON}
style={patternStyle}
onClick={(e) =>
e.feature.setProperty('focus', !e.feature.getProperty('focus'))
}
onMouseover={(e) => {
onTooltip({
x: e.offset.x,
y: e.offset.y,
text: e.feature.getProperty('area1'),
});
map.data.overrideStyle(e.feature, {
fillOpacity: 0.6,
strokeWeight: 4,
strokeOpacity: 1,
});
}}
onMouseout={() => {
onTooltip(null);
map.data.revertStyle();
}}
/>
);
}
export default function DatalayerTutorial6PatternExample() {
const [tooltip, setTooltip] = useState<Tooltip | null>(null);
return (
<NavermapsProvider ncpKeyId="aluya4ff04">
<PatternDefs />
<MapDiv style={{ width: '100%', height: '600px', position: 'relative' }}>
<NaverMap
defaultCenter={{ lat: 36.4203004, lng: 128.31796 }}
defaultZoom={7}
>
<Regions onTooltip={setTooltip} />
</NaverMap>
{tooltip && (
<div
style={{
position: 'absolute',
zIndex: 1000,
left: tooltip.x,
top: tooltip.y,
padding: '5px 10px',
backgroundColor: '#fff',
border: 'solid 2px #000',
fontSize: '14px',
pointerEvents: 'none',
}}
>
{tooltip.text}
</div>
)}
</MapDiv>
</NavermapsProvider>
);
}설명
스타일의 fillColor에 url(#패턴id)를 주면 SVG <pattern>으로 채웁니다. 패턴은 페이지에 숨겨 둔 <svg><defs>에 React로 그리고, style 함수는 컴포넌트 밖에 두어 참조가 바뀌지 않게 합니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
17개 파일을 $.ajax로 받아 개수를 세고 addGeoJson을 17번 부르기 | useJsonAll로 한꺼번에 받아 한 FeatureCollection으로 합치고 <GeoJson> 하나에 전달 |
createElementNS로 만든 svg의 innerHTML에 패턴 넣기 | 숨긴 <svg><defs><pattern>을 JSX로 표시 |
map.data.setStyle과 map.data.addListener | GeoJson의 style prop과 onClick, onMouseover, onMouseout prop |
jQuery로 만든 이름표를 floatPane에 붙이고 css · text로 고치기 | 이름표의 글자와 위치를 state로 관리하고 지도 위의 div로 표시 |
다르게 동작하거나 옮기지 못한 점
- 공식 예제의 패턴 18개는 문서에 적힌 대용량 SVG 라서 옮기지 않고, 같은 방식으로 직접 만든 패턴 6개를 씁니다.
- 공식 예제는 지역마다 패턴을 무작위로 고르지만, 여기서는 지역 이름으로 정해 늘 같은 패턴입니다.