행정구역 GeoJSON 데이터 레이어 표시하기
공식 예제 대응네이버 공식 예제 보기 ↗
17개 시도 경계를 표시합니다. 경계를 클릭해 선택하고 마우스를 올려 지역 이름을 확인합니다.
코드 접기코드 보기
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`,
);
// 색마다 style 함수를 컴포넌트 밖에 둡니다. 렌더마다 새 함수를 만들면 매번 다시 칠합니다.
const makeRegionStyle = (color: string) => (feature: naver.maps.Feature) => {
const focus = feature.getProperty('focus');
return {
fillColor: focus ? '#0f0' : color,
fillOpacity: focus ? 0.6 : 0.0001,
strokeColor: focus ? '#0f0' : color,
strokeWeight: focus ? 4 : 2,
strokeOpacity: focus ? 1 : 0.4,
};
};
const regionStyles = {
red: makeRegionStyle('#ff0000'),
blue: makeRegionStyle('#0050ff'),
};
type RegionColor = keyof typeof regionStyles;
type Tooltip = { x: number; y: number; text: string };
function Regions({
color,
onTooltip,
}: {
color: RegionColor;
onTooltip: (tooltip: Tooltip | null) => void;
}) {
const map = useMap();
const files = useJsonAll<naver.maps.GeoJSON & { features: unknown[] }>(
REGION_PATHS,
);
// 17개 파일의 feature를 한 FeatureCollection으로 합칩니다.
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={regionStyles[color]}
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 DatalayerTutorial2RegionExample() {
const [tooltip, setTooltip] = useState<Tooltip | null>(null);
const [color, setColor] = useState<RegionColor>('red');
return (
<NavermapsProvider ncpKeyId="aluya4ff04">
<MapDiv style={{ width: '100%', height: '600px', position: 'relative' }}>
<NaverMap
defaultCenter={{ lat: 36.4203004, lng: 128.31796 }}
defaultZoom={7}
>
<Regions color={color} 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>
<button onClick={() => setColor((c) => (c === 'red' ? 'blue' : 'red'))}>
경계선 색 바꾸기
</button>
</NavermapsProvider>
);
}설명
17개 파일을 Promise.all로 받아 한 FeatureCollection으로 합쳐 GeoJson 하나에 넘깁니다(합친 값은 useMemo). 선택 상태는 feature.setProperty('focus', ...)로 두고 style 함수가 읽습니다. 이름표는 지도 위의 일반 div이며 위치는 이벤트의 e.offset으로 정합니다.
경계선 색 버튼은 style에 넘기는 함수를 바꿉니다. 색마다 함수를 컴포넌트 밖에 하나씩 두어, 버튼을 누를 때만 이 GeoJson의 feature를 다시 칠합니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
17개 파일을 $.ajax로 받아 개수를 세고 addGeoJson을 17번 부르기 | useJsonAll로 한꺼번에 받아 한 FeatureCollection으로 합치고 <GeoJson> 하나에 전달 |
map.data.setStyle과 map.data.addListener | GeoJson의 style prop과 onClick, onMouseover, onMouseout prop |
jQuery로 만든 이름표를 floatPane에 붙이고 css · text로 고치기 | 이름표의 글자와 위치를 state로 관리하고 지도 위의 div로 표시 |
공식 예제에 더한 것
- 경계선 색 바꾸기 버튼.
style에 넘기는 함수를 바꿔 경계선을 다시 칠하고, 클릭으로 고른 지역(focus)은 그대로 둡니다.