如何在react传单中使用 setRotationAngle

IT技术 reactjs leaflet react-leaflet
2021-05-15 00:12:21

我正在使用react-leaflet地图,并且运行时我必须更新标记的方向,我正在使用leaflet-rotatedmarkerwith的库react-leaflet标记方向在加载和重新加载时工作正常,但在从props接收值后未更新。

<Marker 
 key={1} 
 position={{ lat: position.latitude, lng: position.longitude }} 
 rotationAngle={position.course} 
 rotationOrigin="center" 
 icon={L.icon({
  iconUrl: "xyz.svg", 
  iconSize: [50,50], 
  iconAnchor: [25, 25]})} 
/>

我只想更新rotationAngle接收新的角度值。

请指教,我不知道如何使用setRotationAnglereact-leaflet

谢谢

1个回答

正如这里提到的,在 v2 中不可能再扩展 Marker,所以基本上我们需要复制粘贴整个 Marker 类并添加这个功能。仅供参考,这是我的工作版本RotatedMarker

import React from 'react';
import { Marker as LeafletMarker } from 'leaflet';
import { LeafletProvider, withLeaflet, MapLayer } from 'react-leaflet';
import 'leaflet-rotatedmarker';

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>
    );
  }
}

export default withLeaflet(RotatedMarker);

来源