react
에react-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
가 여러개 렌더됨
Container
에id
주고 자식 요소 찾아서 안보이게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
하나만 나옴