React Leaflet marker rotation

3.5k views Asked by At

I have followed this to build a rotated marker but unfortunately, it doesn't work here is my component which I have created

class RotatedMarker extends MapLayer {

static defaultProps = {
    rotationOrigin: 'center',
};

createLeafletElement(props) {
    const el = new LeafletMarker(props.position, this.getOptions(props));
    this.contextValue = {...props.leaflet, popupContainer: el};
    return el;
}

updateLeafletElement(fromProps, toProps) {
    if (toProps.position !== fromProps.position) {
        this.leafletElement.setLatLng(toProps.position);
    }
    if (toProps.icon !== fromProps.icon) {
        this.leafletElement.setIcon(toProps.icon);
    }
    if (toProps.zIndexOffset !== fromProps.zIndexOffset) {
        this.leafletElement.setZIndexOffset(toProps.zIndexOffset);
    }
    if (toProps.opacity !== fromProps.opacity) {
        this.leafletElement.setOpacity(toProps.opacity);
    }
    if (toProps.draggable !== fromProps.draggable) {
        if (toProps.draggable === true) {
            this.leafletElement.dragging.enable();
        } else {
            this.leafletElement.dragging.disable();
        }
    }
    if (toProps.rotationAngle !== fromProps.rotationAngle) {
        this.leafletElement.setRotationAngle(toProps.rotationAngle);
    }
    if (toProps.rotationOrigin !== fromProps.rotationOrigin) {
        this.leafletElement.setRotationOrigin(toProps.rotationOrigin);
    }
}

render() {
    const {children} = this.props;
    return children == null || this.contextValue == null ? null : (
        <LeafletProvider value={this.contextValue}>{children}</LeafletProvider>
    );
}
}

and this is how I have used the component:

<RotatedMarker
    rotationAngle={120}
    rotationOrigin="center"
    position={[violation.latitude,violation.longitude,]}
    icon={getMarkerIcon().icon}>
</RotatedMarker>

I have tried to call this function this.leafletElement.setRotationAngle(toProps.rotationAngle); directly but I got the following error:

TypeError: this.leafletElement.setRotationAngle is not a function

I'm using react-leaflet V2

1

There are 1 answers

0
kboul On BEST ANSWER

It works for me. Not sure what your setup is but you need to have installed leaflet-rotatedmarker plugin and to import it in your custom component in order not to receive that error.

You should have this

import React from "react";
import { Marker as LeafletMarker } from "leaflet";
import { LeafletProvider, withLeaflet, MapLayer } from "react-leaflet";
import "leaflet-rotatedmarker"; //here import the plugin

class RotatedMarker extends MapLayer {
  static defaultProps = {
    rotationOrigin: "center"
  };
...

Here is a working demo