react-leaflet의 마커 회전

10486 단어 leafletReact-Leaflet
react-leaflet의 Marker를 회전시키는 방법을 조사해, 조금 무리한 느낌이 되고 있습니다만 일단 할 수 있던 정리입니다.

RotableMarker.tsx
import { useEffect, useRef } from "react"; import L from "leaflet"; import { Marker, MarkerProps } from "react-leaflet"; type RotableMarkerProps = MarkerProps & { rotationAngle: number; rotationOrigin: string; }; export const RotableMarker: React.FC<RotableMarkerProps> = (props) => { const markerRef = useRef<any>(); useEffect(() => { const marker = markerRef.current; if (marker) { const proto_setPos = marker._setPos; marker._setPos = (pos: any) => { proto_setPos.call(marker, pos); if (props.rotationAngle) { marker._icon.style[L.DomUtil.TRANSFORM + "Origin"] = props.rotationOrigin; marker._icon.style[L.DomUtil.TRANSFORM] += " rotateZ(" + props.rotationAngle + "deg)"; } }; marker.update(); } }, [props.rotationAngle, props.rotationOrigin]); return ( <Marker ref={markerRef} {...props}> {props.children} </Marker>  ); }; 

사용법으로는 다음이 예입니다.
rotationAngle에서 회전 각도를 45도, rotationOrigin에서 CSS의 transform-origin을 지정합니다.

App.tsx
import L, { LatLngExpression } from "leaflet"; import "leaflet/dist/leaflet.css"; import { MapContainer, TileLayer } from "react-leaflet"; import { RotableMarker } from "./RotableMarker"; L.Icon.Default.imagePath = "//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/images/"; const App = () => { const position: LatLngExpression = [51.505, -0.09]; return ( <MapContainer center={position} zoom={13} scrollWheelZoom={false}> <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <RotableMarker position={position} rotationAngle={45} rotationOrigin="center" /> </MapContainer>  ); }; export default App; 

결과는 다음과 같이 회전합니다.


참고


  • How to dynamically move and rotate marker in react-leaflet?
  • Leaflet Rotated Marker
  • 좋은 웹페이지 즐겨찾기