React - ReactNaverMaps DrawingManager

이호현·2024년 12월 11일
0

React

목록 보기
14/14

reactreact-naver-maps DrawingManager 적용하기
...은 중간 코드 생략 표시
타입은 귀찮아서 any 몇개 그냥 씀

...
import { Container as MapDiv, NaverMap, Polygon } from 'react-naver-maps'
...
const Map = () => {
  const [center, setCenter] = useState<naver.maps.LatLng>()
  const [polygons, setPolygons] = useState<naver.maps.LatLng[][][]>([])
  const DrawingManagerRef = useRef<naver.maps.drawing.DrawingManager | null>(null)

  const mapRef = useCallback(
    (node: any) => {
      if (node !== null && node.zoom && !DrawingManagerRef.current) {
        naver.maps.Event.once(node, 'init', () => {
          DrawingManagerRef.current = new naver.maps.drawing.DrawingManager({
            map: node,
            drawingControl: [naver.maps.drawing.DrawingMode.HAND, naver.maps.drawing.DrawingMode.POLYGON],
            drawingControlOptions: {
              position: naver.maps.Position.TOP_CENTER,
            },
            polygonOptions: {
              strokeColor: 'blue',
              strokeWeight: 1,
            },
          })
      
          DrawingManagerRef.current.addListener(naver.maps.drawing.DrawingEvents.ADD, (e: any) => {
            const newPolygon = e.paths._array[0]._array

            setPolygons((prev) => prev.concat([newPolygon.concat(newPolygon[0])]))

            e.setMap(null) // 폴리곤 그리고 폴리라인 지우기
          })
        })
      }
    }, []
  )

  return (
    <Container>
      <MapDiv>
        <NaverMap center={center} ref={mapRef}>
          {polygons.map((polygon: naver.maps.LatLng[][], idx: number) => (
            <Polygon
              key={`${idx}`}
              fillColor='blue'
              fillOpacity={0.2}
              strokeColor='blue'
              strokeWeight={1}
              paths={polygon}
            />
          ))}
        </NaverMap>
      </MapDiv>
...
    </Container>
  )
})
...

이렇게 했더니 DrawingManager가 여러개 렌더됨
Containerid주고 자식 요소 찾아서 안보이게 css처리 했다가 뭔가 별로라서 다른 방법으로 해결함

...
const [mapRef, setMapRef] = useState<naver.maps.Map | null>(null)
...
useEffect(() => {
  if (mapRef) {
    naver.maps.Event.once(mapRef, 'init', () => {
      DrawingManagerRef.current = new naver.maps.drawing.DrawingManager({
        map: mapRef,
        drawingControl: [naver.maps.drawing.DrawingMode.HAND, naver.maps.drawing.DrawingMode.POLYGON],
        drawingControlOptions: {
          position: naver.maps.Position.TOP_CENTER,
        },
        polygonOptions: {
          strokeColor: Colors.Primary.Main,
          strokeWeight: 1,
        },
      })
	
      DrawingManagerRef.current.addListener(naver.maps.drawing.DrawingEvents.ADD, (e: any) => {
        const newPolygon = e.paths._array[0]._array

        setPolygons((prev) => prev.concat([newPolygon.concat(newPolygon[0])]))

        e.setMap(null)
      })
    })
  }
}, [mapRef])
...
<NaverMap center={center} ref={setMapRef}
...

이렇게 수정하니 DrawingManager 하나만 나옴

profile
평생 개발자로 살고싶습니다

0개의 댓글