Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
BB-D opened this issue Jul 17, 2023 · 0 comments

Comments

@BB-D
Copy link

BB-D commented Jul 17, 2023

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant