JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://api.mapbox.com/mapbox.js/plugins/leaflet-geodesy/v0.1.0/leaflet-geodesy.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<div id="map"></div>
CSS
#map {
height: 500px;
}
JavaScript
var map = L.map("map").setView([38.868605, -77.011669], 12.9);
L.tileLayer('https://stamen-tiles.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var line = turf.lineString([
[-77.031669, 38.878605],
[-77.029609, 38.881946],
[-77.020339, 38.884084],
[-77.025661, 38.885821],
[-77.021884, 38.889563],
[-77.019824, 38.892368]
]);
var pt = turf.point([-77.037076, 38.884017]); // Miss the point [77.02996941477018, 38.881361463229524]
//var pt = turf.point([-77.017076, 38.884017]); // Find the exact point [-77.020339, 38.884084]
//var pt = turf.point([-77.017076, 38.888017]); // Miss the point [-77.02155577034745, 38.89000993406574]
//var pt = turf.point([-77.037076, 38.892017]); // Find the exact point [-77.025661, 38.885821]
var snapped = turf.nearestPointOnLine(line, pt, {units: 'meters'});
snapped.properties['marker-color'] = '#00f';
//addToMap
var addToMap = [line, snapped];
console.log("snapped:", snapped);
// add a marker to the map
L.geoJson(addToMap).addTo(map);