Alex Chernilov
Alex Chernilov

Reputation: 303

React-Leaflet rotate icon

In my old leaflet application I used this code to rotate an icon and it worked perfectly. Now, I'm trying to move the code to react-leaflet but cannot figure out how to apply this. I know it should be possible via custom components, I tried to create some kind on RotatedMarker (based on Marker.js in the src), but as I'm new to all that, I could not make it work... Can anyone point me in the right direction?

Thanks,

Alex

Upvotes: 1

Views: 3467

Answers (2)

tnaber
tnaber

Reputation: 21

I found another way, try constructing the icon like this:

var icon = L.divIcon({
    iconSize: [20, 20],
    iconAnchor: [10, 10],
    className: 'yourClassName',
    html: `<img 
    style="transform: rotate(80deg);"
    height="20" 
    width="20" 
    src='path/to/icon'>`
})

And then add it to your marker:

<Marker position={position} icon={icon} />

Upvotes: 2

Alex Chernilov
Alex Chernilov

Reputation: 303

Ok. This is what I did to make it work. Not sure it should be done this way, but it seems to work.

export default class RotatedMarker extends Marker {

    componentDidMount() {

        super.componentDidMount();
        this.leafletElement.setIconAngle(this.props.rotation);
    }


    componentWillUpdate(nextProps, nextState) {
        if (nextProps.rotation) {
            this.leafletElement.setIconAngle(nextProps.rotation);
        }
    }
}

Upvotes: 1

Related Questions