react-leafletのMarkerを回転させる
10698 ワード
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;
参考
Author And Source
この問題について(react-leafletのMarkerを回転させる), 我々は、より多くの情報をここで見つけました https://qiita.com/two_pack/items/d05d640d6dfa52ccbf72著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .