bbecquet / Leaflet.PolylineDecorator

A plug-in for the JS map library Leaflet, allowing to define patterns (like dashes, arrows, icons, etc.) on Polylines.
MIT License
496 stars 114 forks source link

Show/Hide Polylinedecorators dynamically (based on other variable) in React Leaflet #111

Open BB-D opened 1 year ago

BB-D commented 1 year ago

I have succesfully implemented Polylinedecorators, however I am not able to easily hide them based on a boolean statement in React Leaflet. 'Normal' polylines are displayed/hided based on a certain variable (for example the boolean 'certainBool'). I can not seem to find an easy way to easily add polyLineDecorators as a JSX component directly, without using the addToMap functionality. The problem with the addToMap functionality is that it is difficult to remove the elements added to the map in this way. Especially as my polylines (and polylinedecorators) are created in a (large) for loop. See the following code:

import React from 'react';
import { Polyline, useMap } from 'react-leaflet';
import 'leaflet-polylinedecorator';
import L from 'leaflet';

function showTrajectories() {
  const { trajectories, certainBool } = React.useContext(certainContext);

  const arrow = [
    {
      offset: '52%',
      endOffset: '52%',
      repeat: '100%',
      symbol: L.Symbol.arrowHead({
        pixelSize: 3,
        polygon: false,
        pathOptions: { stroke: true, opacity: 0.4 },
      }),
    },
  ];

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

    var decorator = L.polylineDecorator(polyline, {
      id: id,
      patterns,
    });
    decorator.addTo(map);
    return null;
  }

  if (trajectories.length > 0) {
    return trajectories.map((trajectory, i) => {
      if (certainBool) {
        return (
          <>
            <PolylineDecorator polyline={trajectory.coordinates} patterns={arrow} id={i} />
            <Polyline
              positions={trajectory.coordinates}
              className='line'
              key={i}
              noClip={true}
            ></Polyline>
          </>
        );
      }
    });
  }
}

export default showTrajectories;