Search code examples
reactjsleafletreact-leafletreact-leaflet-v4

Rotate marker in react-leaflet v4 - React Typescript


I´m having trouble trying to rotate the marker in react-leaflet.

I have seen some examples where it is done with an older version of react-leaflet using leaflet-rotatedmarker. See below... have tried using both these examples without any result, have also tried to override css with transform: rotate(18deg);, but that did not work either. Any help will be appreciated

package.json:

  "dependencies": {
     ...
    "@types/leaflet": "^1.9.0",
    "@types/node": "^16.7.13",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "leaflet": "^1.9.2",
    "leaflet-rotatedmarker": "^0.2.0",,
    "react-leaflet": "^4.1.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.4.2"
  },

Result:

import 'leaflet-rotatedmarker';
import L, { LatLngBoundsLiteral, LatLngBounds, Icon, LatLng, map } from "leaflet";
...
let m = L.marker([51.505, -0.09]).addTo(map);
m.setRotationAngle(180);

error1 error

Working example with a older react-leaflet version: codesandbox stackoverflow question


Solution

  • Add leaflet-rotatedmarker: npm source

    If you are using typescript use:

    yarn add @types/leaflet-rotatedmarker
    
    
    import { MapContainer, Marker, TileLayer, Tooltip } from "react-leaflet";
    import 'leaflet-rotatedmarker';
    ....
                  //add rotationAngle
                  <Marker
                    icon={myIcon}
                    key={data.key}
                    position={[data.latitude, data.longitude]}
                    rotationAngle={data.angle}
                  >
                  </Marker>