简体   繁体   中英

React Leaflet marker rotation

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM