0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react-leafletのMarkerを回転させる

Posted at

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;

結果は以下のように回転しています。
capture.png

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?