What is @turf/nearest-point-on-line?
@turf/nearest-point-on-line is a module from the Turf.js library that allows you to find the nearest point on a line from a given point. This can be useful in various geospatial analyses, such as snapping a point to a road network or finding the closest point of interest along a path.
What are @turf/nearest-point-on-line's main functionalities?
Find Nearest Point on Line
This feature allows you to find the nearest point on a given line from a specified point. In the code sample, a line and a point are defined, and the nearest point on the line to the given point is calculated and logged.
const turf = require('@turf/turf');
const line = turf.lineString([[0, 0], [2, 2], [3, 3]]);
const point = turf.point([1, 2]);
const snapped = turf.nearestPointOnLine(line, point);
console.log(snapped);
Other packages similar to @turf/nearest-point-on-line
geolib
Geolib is a library for geospatial calculations in JavaScript. It provides various functions for distance calculations, finding nearest points, and more. Compared to @turf/nearest-point-on-line, Geolib offers a broader range of geospatial utilities but may not be as specialized in line-specific operations.
geodesy
Geodesy is a library for geodesic and trigonometric calculations. It includes functions for distance calculations, bearing, and more. While it provides some similar functionalities, it is more focused on geodesic calculations rather than finding the nearest point on a line.
@turf/nearest-point-on-line
nearestPointOnLine
Takes a Point and a LineString and calculates the closest Point on the (Multi)LineString.
Parameters
Examples
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]);
var snapped = turf.nearestPointOnLine(line, pt, {units: 'miles'});
var addToMap = [line, pt, snapped];
snapped.properties['marker-color'] = '#00f';
Returns Feature<Point> closest point on the line
to point
. The properties object will contain four values: index
: closest point was found on nth line part, multiFeatureIndex
: closest point was found on the nth line of the MultiLineString
, dist
: distance between pt and the closest point, location
: distance along the line between start and the closest point.
This module is part of the Turfjs project, an open source module collection dedicated to geographic algorithms. It is maintained in the Turfjs/turf repository, where you can create PRs and issues.
Installation
Install this single module individually:
$ npm install @turf/nearest-point-on-line
Or install the all-encompassing @turf/turf module that includes all modules as functions:
$ npm install @turf/turf