turf.segmentEach
What is turf.segmentEach?
turf.segmentEach walks every consecutive pair of coordinates in any LineString, MultiLineString, Polygon, or MultiPolygon boundary — yielding each pair as a two-vertex LineString Feature.
turf.segmentEach(geojson, callback) → voidThe callback receives (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex).
When would you use turf.segmentEach?
Use turf.segmentEach whenever an algorithm operates on line segments rather than whole lines — computing per-segment lengths or bearings, intersecting segments against a query line, or rendering an edge-level dataset from a network.
It also pairs well with spatial indices: build an R-tree over segments for fast segment-level queries instead of iterating features manually.
1turf.segmentEach(network, (segment) => {
2 const bearing = turf.bearing(
3 turf.point(segment.geometry.coordinates[0]),
4 turf.point(segment.geometry.coordinates[1])
5 );
6 segments.push({ segment, bearing });
7});FAQs
How do I install Turf.js to use this function?
Install npm install @turf/meta and import import { segmentEach } from '@turf/meta', or use turf.segmentEach through @turf/turf.
Does segmentEach visit polygon rings?
Yes. Every closed ring (outer and holes) contributes its consecutive coordinate pairs as segments — which is useful for per-edge polygon analysis.
Are segments cloned or referenced?
Each yielded segment is a freshly constructed LineString Feature whose coordinates reference the original positions. Mutating the positions affects the underlying geometry — be careful.
When should I use segmentEach vs coordEach?
Use segmentEach when your algorithm works in pairs (edges). Use coordEach when you only care about individual vertices. A segment is the edge between two vertices, so they answer different questions.