This plugin is an extension for Leaflet.Draw that includes a new set of tools which allow the user to select a line and trace along it.
It requires Leaflet.Draw and @turf/turf. It also includes code based on Leaflet.AlmostOver and Leaflet.GeometryUtil, altered to fit the needs of this plugin.
Play with it here
To include it in your app using a cdn add the following to the top of your html
<link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw-src.css" />
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@6/turf.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet-trace@0.3.1/dist/leaflet.trace.css" />
<script type="module" src="https://unpkg.com/leaflet-trace@0.3.1/dist/leaflet.trace.js"></script>
If you install using npm adding this to your html should do the trick:
<link rel="stylesheet" type="text/css" href="../node_modules/leaflet/dist/leaflet.css"/>
<script src="../node_modules/leaflet-draw/dist/leaflet.draw.js"></script>
<script src="../node_modules/@turf/turf/turf.min.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="../node_modules/leaflet-trace/dist/leaflet.trace.css"/>
<script src="../node_modules/leaflet-trace/dist/leaflet.trace.js"></script>
Leaflet.Trace mainly extends L.Control.Draw to add a new set of 3 tools that work together to allow users to trace along a selected line and snap a marker to a selected line.
It is initalized similarly to L.Control.Draw, with the addition of a trace option.
new L.Control.Trace({
trace: true,
draw: {
circlemarker: false, //Leaflet.Trace includes a slightly altered version of the L.Draw.CircleMarker
},
edit: {
featureGroup: drawnItems,
},
}).addTo(map);
Leaflet.Trace works with L.geoJSON layers that contain a FeatureCollection made up of LineString and MultiLineString features.
For Leaflet.Trace to be able to detect your L.geoJSON you need to give it an attribute of "trace" set to "true".
const lines = L.geoJSON(featureCollection).addTo(map);
lines.trace = true;