I am currently working on a trail mapping Next.js react app where I fetch data from OpenStreetMap and illustrate trails on a map using leaflet polyline. Some trails have the tag oneway= ‘yes’ which I would like to represent visually using arrows on the polyline itself, that way it would be easy to tell which direction each trail went.
I have searched and tried many different avenues to try and replicate this feature in my app, using leaflet plugins such as leaflet-polylineDecorator or leaflet-arrowheads. I even tried rendering a bunch of markers and rotating them to point towards the next node, but I didn’t manage to make it work and it seemed too complicated a solution for something so simple.
I am looking at implementing a simple and lightweight solution to avoid slowing the app down. Is there an easy solution which I am missing?
2
Answers
I ended up solving the issue I had with the leaflet-polylineDecorator not being found even after installing.
You have to run :
pnpm install --save-dev @types/leaflet-polylinedecorator
I then created a react component in which I added a useEffect hook to add the decorator to the map and then added it into my map component.
You can relatively easy adding decoration with
leaflet.polylineDecorator
.You’ll need to create a decorator for each feature that is
oneway = 'yes'
. I recommend to add the decorators to a separateL.FeatureGroup
(instead to the map directly) so you can easily remove, show or hide them depending on the zoom level.Here is an example (using vanilla JavaScript and a test GeoJSON with polylines and a property
oneway
; it will require some adaptation to your dataset and for Next.js):The file
trails.geojson
can be found here.I also uploaded the code to a GitHub repository here and a demo can be found here.
I think using a library such as
leaflet.polylineDecorator
orleaflet-arrowheads
is probably the most lightweight solution as you would need to manipulate the SVG paths manually otherwise.Addendum: In
leaflet.polylineDecorator
‘sREADME.md
there is a section recommending two light-weight alternatives for simpler cases.Leaflet.TextPath
could be worth to be investigated.