I have created polyline using react-leaflet, I want to show direaction on polyline using polylinedacorator.But I don't know how to do that with react-leaflet. I found multiple examples with leaflet, but not with react-leaflet
const polyline = [[51.505, -0.09], [51.51, -0.1], [51.51, -0.12]]
export default class VectorLayersExample extends Component<{}> {
render() {
return (
<Map center={center} zoom={13}>
<TileLayer
attribution='&copy <a
href="http://osm.org/copyright">OpenStreetMap</a>
contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Polyline color="lime" positions={polyline} />
</Map>
)
}
Can any one tell me how to use polylinedacorators with above code
Leaflet.PolylineDecorator
could be integrated with React-Leaflet
as follows:
a) install leaflet
and leaflet-polylinedecorator
packages: npm i leaflet leaflet-polylinedecorator
b) once installed, the following component demonstrates how to utilize Polyline
component with L.polylineDecorator
:
import React, { useRef, useEffect } from "react";
import { Map, TileLayer, Polyline, withLeaflet } from "react-leaflet";
import L from "leaflet";
import "leaflet-polylinedecorator";
const PolylineDecorator = withLeaflet(props => {
const polyRef = useRef();
useEffect(() => {
const polyline = polyRef.current.leafletElement; //get native Leaflet polyline
const { map } = polyRef.current.props.leaflet; //get native Leaflet map
L.polylineDecorator(polyline, {
patterns : props.patterns
}).addTo(map);
}, []);
return <Polyline ref={polyRef} {...props} />;
});
Usage
function MyMap(props) {
const { center, zoom } = props;
const polyline = [[57, -19], [60, -12]];
const arrow = [
{
offset: "100%",
repeat: 0,
symbol: L.Symbol.arrowHead({
pixelSize: 15,
polygon: false,
pathOptions: { stroke: true }
})
}
];
return (
<Map center={center} zoom={zoom}>
<TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" />
<PolylineDecorator patterns={arrow} positions={polyline} />
</Map>
);
}