简体   繁体   English

polylinedac​​orator 与反应传单 4

[英]polylinedacorator with react leaflet 4

I am trying to include arrows to the Polyline in react-leaft.我正在尝试在 react-left 中包含指向折线的箭头。 For that I am using polylinedecorator plugin.为此,我正在使用polylinedecorator插件。 There is a similar post on this platform.这个平台上有一个类似的帖子 However, it uses withLeaflet module which is not supported in react-leaflet 4.0.但是,它使用了 react-leaflet 4.0 中不支持的withLeaflet模块。 How can I make it run without using 'withLeaflet'.如何在不使用“withLeaflet”的情况下使其运行。 I have tried to implement it with the hooks.我试图用钩子来实现它。 However, it does not work and need some assistance, how can I make it run.但是,它不起作用,需要一些帮助,我怎样才能让它运行。

export default function App(): JSX.Element {
   const polylineRef = useRef<any>(null);

  const arrow = [
{
  offset: "100%",
  repeat: 0,
  symbol: L.Symbol.arrowHead({
    pixelSize: 15,
    polygon: false,
    pathOptions: { stroke: true }
  })
}];


useEffect(()=>{
    L.polylineDecorator(polylineRef.current,{
      patterns: arrow
    })
}, [polylineRef]);

return (

  <MapContainer center={center} zoom={13} scrollWheelZoom={true} style={{height: 'calc(100% - 30px)'}}>
    <TileLayer
      attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
    />
    {currentData?.movingActors.map(line =>(<Polyline key={line.id} 
    positions={[line.startLocation, line.endLocation] } ref={polylineRef} 
    color={modeColor(line.mode)}
    />  
    ))}
  </MapContainer>
</>);}

CHANGES MADE TO THE ACCEPTED ANSWER TO MAKE IT RUN对接受的答案进行更改以使其运行

function PolylineDecorator({ patterns, polyline,color }) {
  const map = useMap();
  useEffect(() => {
    if (!map) return;

   L.polyline(polyline, {color}).addTo(map);  // added color property
    L.polylineDecorator(polyline, {
      patterns,
      
    }).addTo(map);
  }, [map]);
 
  return null;
}


 {currentData?.movingActors.map(line =>(<PolylineDecorator key={line.id} patterns ={arrow} polyline={position}  color = {modeColor(line.mode)} />) ) }   //here I used color parameters to dynamically add colors

What you need is a custom react functional component that returns null and has a useEffect with the code to initialize the plugin:你需要的是一个自定义的 react 功能组件,它返回 null 并且有一个useEffect代码来初始化插件:

function PolylineDecorator({ patterns, polyline }) {
  const map = useMap();

  useEffect(() => {
    if (!map) return;

    L.polyline(polyline).addTo(map);
    L.polylineDecorator(polyline, {
      patterns
    }).addTo(map);
  }, [map]);

  return null;
}

and then use it like:然后像这样使用它:

<MapContainer...>
      <TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" />
      <PolylineDecorator patterns={arrow} polyline={polyline} />
 </MapContainer>

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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