Line operations: slicing, chunking and nearest points
Quick answer
This tutorial works along a line by mileage: along for a point at a distance, lineSlice and lineSliceAlong for extracting a segment, lineChunk for equal-length pieces, lineOffset for parallel lines, and nearestPointOnLine with pointToLineDistance for projection. It details the properties.dist, index and location fields and the shared units requirement. You will be able to build route and corridor tooling.
Key points
- Pass the same units to turf.length and turf.along, since kilometers versus meters differ by a factor of 1000.
- Read properties.location and properties.index from nearestPointOnLine for mileage and segment info.
- Use positive and negative distances in turf.lineOffset to place lines on either side.
Example
var line = turf.lineString([
[116.391263, 39.907359],
[116.407000, 39.899000],
[116.430000, 39.910000]
]);
var total = turf.length(line, { units: 'kilometers' });
console.log('全长', total.toFixed(3), '公里');
[0, 0.5, 1, total].forEach(function (d) {
var p = turf.along(line, d, { units: 'kilometers' });
console.log(d, turf.getCoord(p));
});var a = turf.point([116.400000, 39.903000]);
var b = turf.point([116.425000, 39.909500]);
var partByPoints = turf.lineSlice(a, b, line);
var partByKm = turf.lineSliceAlong(line, 0.8, 2.4, { units: 'kilometers' });
console.log(partByPoints.geometry.coordinates.length);
console.log(partByKm.geometry.coordinates.length);
Notes
- along beyond the line length returns the endpoint instead of throwing, which can hide bad input.
- Points that project to the same spot make lineSlice return a zero-length degenerate line.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Line operations: slicing, chunking and nearest points. https://www.jingweizhi.com/en/turf/tutorials/line-ops.html (accessed 2026-11-03).