React Naver Maps
136

예제/공식 예제/지도 유형

두 가지의 지도 유형을 함께 사용하기

공식 예제 대응네이버 공식 예제 보기 ↗

지도 화면이 한국 경계를 벗어나면 OSM으로, 안에 들어오면 네이버 지도로 바꿉니다.

코드 접기코드 보기
import { useMemo, useRef, useState } from 'react';
import {
  NavermapsProvider,
  Container as MapDiv,
  NaverMap,
  useNavermaps,
} from 'react-naver-maps';
import { defaultMapTypes } from './example-ui-a';

function NaverOsmMapContent() {
  const navermaps = useNavermaps();
  const mapRef = useRef<naver.maps.Map>(null);
  const [mapTypeId, setMapTypeId] = useState<string>('normal');
  // 줌 효과 뒤 첫 idle은 건너뜁니다(공식 예제가 zooming 동안 idle 리스너를 떼는 것과 동일).
  const skipIdleRef = useRef(false);

  const { mapTypes, korea } = useMemo(() => {
    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({
        ...defaultMapTypes(navermaps),
        osm,
      }),
      korea: new navermaps.LatLngBounds(
        new navermaps.LatLng(30.1391277, 115.0607471),
        new navermaps.LatLng(48.940448, 139.7803655),
      ),
    };
  }, [navermaps]);

  // 지도 화면이 한국 경계를 벗어나면 OSM으로, 안에 들어오면 네이버 일반 지도로 바꿉니다.
  function checkBounds() {
    if (skipIdleRef.current) {
      skipIdleRef.current = false;
      return;
    }
    const bounds = mapRef.current?.getBounds();
    if (!bounds) return;
    // 한국 안으로 돌아오면 OSM일 때만 일반 지도로 돌립니다. 사용자가 고른 위성·지형은 유지합니다.
    const inKorea = korea.hasBounds(bounds);
    setMapTypeId((prev) =>
      inKorea ? (prev === 'osm' ? 'normal' : prev) : 'osm',
    );
  }

  return (
    <NaverMap
      ref={mapRef}
      defaultCenter={{ lat: 37.3595704, lng: 127.105399 }}
      defaultZoom={7}
      mapTypes={mapTypes}
      mapTypeId={mapTypeId}
      onMapTypeIdChanged={setMapTypeId}
      mapTypeControl
      mapTypeControlOptions={{ style: navermaps.MapTypeControlStyle.BUTTON }}
      onZoomstart={() => {
        skipIdleRef.current = true;
      }}
      onIdle={checkBounds}
    />
  );
}

export default function MapTypesTutorial5NaverOsmExample() {
  return (
    <NavermapsProvider ncpKeyId="aluya4ff04">
      <MapDiv style={{ width: '100%', height: '600px' }}>
        <NaverOsmMapContent />
      </MapDiv>
    </NavermapsProvider>
  );
}

설명

onIdle에서 ref로 받은 지도의 getBounds()를 한국 경계와 LatLngBounds.hasBounds로 비교해 normal과 osm 중 하나를 고릅니다. 경계는 레지스트리와 함께 useMemo로 한 번만 만듭니다.

복사해 쓸 때 함께 필요한 파일

이 예제는 사이트의 보조 코드를 씁니다. 아래 파일도 같은 경로에 두거나 내용을 옮겨 주세요.

React로 옮기며 바꾼 점

네이버 공식 예제이 예제
map.mapTypes.set으로 지도의 기본 레지스트리에 osm 더하기기본 네 유형과 osm을 넣은 레지스트리를 useMemo로 만들어 mapTypes에 전달
idle 리스너에서 getMapTypeId(), setMapTypeId()로 지도 유형 바꾸기mapTypeId를 state로 관리하고 onIdle에서 설정. 컨트롤로 바꾼 값은 onMapTypeIdChanged로 state에 반영
zooming 동안 idle 리스너를 떼었다가 다음 idle에 다시 붙이기onZoomstart에서 ref 플래그를 설정해 다음 idle 한 번을 건너뛰기