turf.nearestPointOnLine
What is turf.nearestPointOnLine?
turf.nearestPointOnLine projects an input Point onto a LineString and returns a Point Feature at the closest point on the line. The returned feature carries dist (distance from input to projected point), location (distance along the line from its start), and index (segment index) on its properties.
turf.nearestPointOnLine(line, point, options?) → Feature<Point>Options include:
units—'kilometers'(default),'meters','miles','nauticalmiles','radians','degrees'
When would you use turf.nearestPointOnLine?
Use turf.nearestPointOnLine for snapping interactions — projecting a click or marker drop onto a road, rail, or river polyline. It powers "drag to snap" UI patterns on MapLibre, generates linear referencing (mileposts along a route) in Node.js, and is the basis for progress tracking on a route (how far along are you?).
The location property in particular is useful: feed it to turf.along to reconstruct the exact snapped point, chunk the line at that offset, or update a progress bar in a fitness tracker.
undefinedFAQs
What do dist, location, and index represent?
dist is the perpendicular (or endpoint) distance from the input point to the line. location is the distance from the start of the line to the projected point along the line. index is the index of the segment on which the projection landed.
Is this the same as turf.pointToLineDistance?
pointToLineDistance returns only the distance value. nearestPointOnLine returns the full projected point plus distance metadata — use this when you need the snapped location, not just its distance.
How do I install just nearestPointOnLine?
npm install @turf/nearest-point-on-line. Its dependencies include @turf/distance, @turf/bearing, @turf/destination, and @turf/helpers.
Does it handle MultiLineString?
Yes — it iterates across all parts and returns the globally nearest projection.