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='© <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;