0
# Turf.js
1
2
Turf.js is a comprehensive modular geospatial analysis engine written in JavaScript that enables developers to perform advanced spatial analysis and geometric operations using GeoJSON data. The library provides over 100 specialized functions for creating geographic data, performing spatial analysis, data classification, and statistical operations on geographic features like points, lines, and polygons.
3
4
## Package Information
5
6
- **Package Name**: @turf/turf
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install @turf/turf`
10
11
## Core Imports
12
13
```typescript
14
import * as turf from "@turf/turf";
15
```
16
17
For selective imports:
18
19
```typescript
20
import { point, polygon, distance, area, buffer } from "@turf/turf";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const turf = require("@turf/turf"); // Full library
27
const { point, polygon, distance } = require("@turf/turf"); // Selective
28
```
29
30
## Basic Usage
31
32
```typescript
33
import { point, polygon, distance, area, buffer, booleanPointInPolygon } from "@turf/turf";
34
35
// Create GeoJSON geometries
36
const pt1 = point([-75.343, 39.984]);
37
const pt2 = point([-75.534, 39.123]);
38
const poly = polygon([[
39
[-5, -5], [5, -5], [5, 5], [-5, 5], [-5, -5]
40
]]);
41
42
// Perform spatial calculations
43
const dist = distance(pt1, pt2, { units: 'miles' });
44
const polyArea = area(poly);
45
const buffered = buffer(pt1, 1, { units: 'kilometers' });
46
47
// Spatial relationships
48
const pointInside = booleanPointInPolygon(pt1, poly);
49
50
console.log(`Distance: ${dist} miles`);
51
console.log(`Area: ${polyArea} square meters`);
52
console.log(`Point inside polygon: ${pointInside}`);
53
```
54
55
## Architecture
56
57
Turf.js is built around several key components:
58
59
- **Foundational Helpers**: Core GeoJSON creation functions and utilities (`@turf/helpers`, `@turf/meta`, `@turf/invariant`)
60
- **Spatial Measurement**: Distance, area, length, and bearing calculations
61
- **Geometric Operations**: Buffer, intersection, union, difference operations using JSTS engine
62
- **Boolean Operations**: Spatial relationship testing (contains, intersects, touches, etc.)
63
- **Data Transformation**: Coordinate transformation, projection, and geometry manipulation
64
- **Spatial Analysis**: Clustering, interpolation, statistical analysis, and grid generation
65
- **Type System**: Full TypeScript support with GeoJSON-compliant type definitions
66
67
All functions expect data in WGS84 longitude/latitude coordinates and return GeoJSON-compliant data structures.
68
69
## Capabilities
70
71
### Foundational Helpers
72
73
Core GeoJSON creation functions, coordinate utilities, and foundational type definitions that support all other Turf operations.
74
75
```typescript { .api }
76
// GeoJSON Feature creation
77
function point<P>(coordinates: Position, properties?: P, options?: {bbox?: BBox; id?: Id}): Feature<Point, P>;
78
function polygon<P>(coordinates: Position[][], properties?: P, options?: {bbox?: BBox; id?: Id}): Feature<Polygon, P>;
79
function lineString<P>(coordinates: Position[], properties?: P, options?: {bbox?: BBox; id?: Id}): Feature<LineString, P>;
80
function featureCollection<G, P>(features: Array<Feature<G, P>>, options?: {bbox?: BBox; id?: Id}): FeatureCollection<G, P>;
81
82
// Unit conversion utilities
83
function convertLength(length: number, originalUnit?: Units, finalUnit?: Units): number;
84
function convertArea(area: number, originalUnit?: AreaUnits, finalUnit?: AreaUnits): number;
85
function radiansToLength(radians: number, units?: Units): number;
86
function lengthToRadians(distance: number, units?: Units): number;
87
88
// Coordinate utilities
89
function bearingToAzimuth(bearing: number): number;
90
function azimuthToBearing(angle: number): number;
91
function radiansToDegrees(radians: number): number;
92
function degreesToRadians(degrees: number): number;
93
```
94
95
[Foundational Helpers](./helpers.md)
96
97
### Geometry Iteration and Manipulation
98
99
Utilities for iterating over and manipulating GeoJSON geometries, coordinates, and properties using functional programming patterns.
100
101
```typescript { .api }
102
// Coordinate iteration
103
function coordEach(geojson: AllGeoJSON, callback: (currentCoord: number[], coordIndex: number, featureIndex: number, multiFeatureIndex: number, geometryIndex: number) => void, excludeWrapCoord?: boolean): void;
104
function coordReduce<Reducer>(geojson: AllGeoJSON, callback: (previousValue: Reducer, currentCoord: number[], coordIndex: number, featureIndex: number, multiFeatureIndex: number, geometryIndex: number) => Reducer, initialValue?: Reducer): Reducer;
105
106
// Feature iteration
107
function featureEach<G, P>(geojson: Feature<G, P> | FeatureCollection<G, P> | Feature<GeometryCollection, P>, callback: (currentFeature: Feature<G, P>, featureIndex: number) => void): void;
108
function featureReduce<Reducer, G, P>(geojson: Feature<G, P> | FeatureCollection<G, P> | Feature<GeometryCollection, P>, callback: (previousValue: Reducer, currentFeature: Feature<G, P>, featureIndex: number) => Reducer, initialValue?: Reducer): Reducer;
109
110
// Geometry iteration
111
function geomEach<G, P>(geojson: Feature<G, P> | FeatureCollection<G, P> | G | GeometryCollection | Feature<GeometryCollection, P>, callback: (currentGeometry: G, featureIndex: number, featureProperties: P, featureBBox: BBox, featureId: Id) => void): void;
112
function geomReduce<Reducer, G, P>(geojson: Feature<G, P> | FeatureCollection<G, P> | G | GeometryCollection | Feature<GeometryCollection, P>, callback: (previousValue: Reducer, currentGeometry: G, featureIndex: number, featureProperties: P, featureBBox: BBox, featureId: Id) => Reducer, initialValue?: Reducer): Reducer;
113
```
114
115
[Geometry Iteration](./meta.md)
116
117
### Input Validation and Data Extraction
118
119
Utilities for validating GeoJSON inputs and extracting coordinates and geometries safely with type checking.
120
121
```typescript { .api }
122
function getCoord(coord: Feature<Point> | Point | number[]): number[];
123
function getCoords<G>(coords: any[] | Feature<G> | G): any[];
124
function getGeom<G>(geojson: Feature<G> | G): G;
125
function getType(geojson: Feature<any> | FeatureCollection<any> | Geometry, name?: string): string;
126
function geojsonType(value: any, type: string, name: string): void;
127
function featureOf(feature: Feature<any>, type: string, name: string): void;
128
function collectionOf(featureCollection: FeatureCollection<any>, type: string, name: string): void;
129
```
130
131
[Input Validation](./invariant.md)
132
133
### Spatial Measurement
134
135
Functions for calculating distances, areas, lengths, angles, and bearings between geographic features using geodesic calculations.
136
137
```typescript { .api }
138
function distance(from: Coord, to: Coord, options?: {units?: Units}): number;
139
function area(geojson: Feature<any> | FeatureCollection<any> | Geometry): number;
140
function length(geojson: Feature<LineString | MultiLineString | Polygon | MultiPolygon>, options?: {units?: Units}): number;
141
function bearing(start: Coord, end: Coord, options?: {final?: boolean}): number;
142
function angle(start: Coord, vertex: Coord, end: Coord, options?: {explementary?: boolean; mercator?: boolean}): number;
143
```
144
145
[Spatial Measurement](./measurement.md)
146
147
### Boolean Spatial Operations
148
149
Functions for testing spatial relationships between geometric features, including intersections, containment, and topology validation.
150
151
```typescript { .api }
152
function booleanPointInPolygon(point: Coord, polygon: Feature<Polygon | MultiPolygon> | Polygon | MultiPolygon, options?: {ignoreBoundary?: boolean}): boolean;
153
function booleanContains(feature1: Feature<any>, feature2: Feature<any>): boolean;
154
function booleanIntersects(feature1: Feature<any>, feature2: Feature<any>): boolean;
155
function booleanOverlap(feature1: Feature<any>, feature2: Feature<any>): boolean;
156
function booleanCrosses(feature1: Feature<any>, feature2: Feature<any>): boolean;
157
function booleanDisjoint(feature1: Feature<any>, feature2: Feature<any>): boolean;
158
function booleanTouches(feature1: Feature<any>, feature2: Feature<any>): boolean;
159
function booleanWithin(feature1: Feature<any>, feature2: Feature<any>): boolean;
160
function booleanEqual(feature1: Feature<any>, feature2: Feature<any>): boolean;
161
```
162
163
[Boolean Operations](./boolean-operations.md)
164
165
### Geometric Operations
166
167
Advanced geometric operations for creating, modifying, and combining geographic features including buffers, intersections, and unions.
168
169
```typescript { .api }
170
function buffer(geojson: FeatureCollection<any> | Feature<any> | Geometry, radius: number, options?: {units?: Units; steps?: number}): FeatureCollection<Polygon> | Feature<Polygon>;
171
function intersect(feature1: Feature<Polygon | MultiPolygon>, feature2: Feature<Polygon | MultiPolygon>, options?: {properties?: GeoJsonProperties}): Feature<Polygon | MultiPolygon> | null;
172
function union(...features: Feature<Polygon | MultiPolygon>[]): Feature<Polygon | MultiPolygon> | null;
173
function difference(feature1: Feature<Polygon | MultiPolygon>, feature2: Feature<Polygon | MultiPolygon>, options?: {properties?: GeoJsonProperties}): Feature<Polygon | MultiPolygon> | null;
174
function convex(geojson: FeatureCollection<any> | Feature<any> | Geometry, options?: {concavity?: number; properties?: GeoJsonProperties}): Feature<Polygon>;
175
function concave(geojson: FeatureCollection<Point>, maxEdge: number, options?: {units?: Units; properties?: GeoJsonProperties}): Feature<Polygon> | null;
176
```
177
178
[Geometric Operations](./geometric-operations.md)
179
180
### Data Generation and Grids
181
182
Functions for generating geometric data including grids, random features, and structured spatial patterns.
183
184
```typescript { .api }
185
function pointGrid(bbox: BBox, cellSide: number, options?: {units?: Units; mask?: Feature<Polygon | MultiPolygon>; properties?: GeoJsonProperties}): FeatureCollection<Point>;
186
function squareGrid(bbox: BBox, cellSide: number, options?: {units?: Units; mask?: Feature<Polygon | MultiPolygon>; properties?: GeoJsonProperties}): FeatureCollection<Polygon>;
187
function hexGrid(bbox: BBox, cellSide: number, options?: {units?: Units; properties?: GeoJsonProperties; mask?: Feature<Polygon | MultiPolygon>; triangles?: boolean}): FeatureCollection<Polygon>;
188
function triangleGrid(bbox: BBox, cellSide: number, options?: {units?: Units; properties?: GeoJsonProperties; mask?: Feature<Polygon | MultiPolygon>}): FeatureCollection<Polygon>;
189
190
// Random generation
191
function randomPoint(count?: number, options?: {bbox?: BBox}): FeatureCollection<Point>;
192
function randomPolygon(count?: number, options?: {bbox?: BBox; num_vertices?: number; max_radial_length?: number}): FeatureCollection<Polygon>;
193
function randomLineString(count?: number, options?: {bbox?: BBox; num_vertices?: number; max_length?: number; max_rotation?: number}): FeatureCollection<LineString>;
194
```
195
196
[Data Generation](./data-generation.md)
197
198
### Spatial Analysis and Statistics
199
200
Advanced spatial analysis functions including clustering, interpolation, statistical analysis, and spatial autocorrelation.
201
202
```typescript { .api }
203
function clustersDbscan(points: FeatureCollection<Point>, maxDistance: number, options?: {units?: Units; minPoints?: number; mutate?: boolean}): FeatureCollection<Point>;
204
function clustersKmeans<P>(points: FeatureCollection<Point, P>, options?: {numberOfClusters?: number; mutate?: boolean}): FeatureCollection<Point, P>;
205
function interpolate(points: FeatureCollection<Point>, cellSize: number, options?: {gridType?: 'point' | 'square' | 'hex' | 'triangle'; property?: string; units?: Units; weight?: number}): FeatureCollection<Point>;
206
function isobands(pointGrid: FeatureCollection<Point>, breaks: number[], options?: {zProperty?: string; commonProperties?: GeoJsonProperties; breaksProperties?: GeoJsonProperties[]}): FeatureCollection<Polygon>;
207
function isolines(pointGrid: FeatureCollection<Point>, breaks: number[], options?: {zProperty?: string; commonProperties?: GeoJsonProperties; breaksProperties?: GeoJsonProperties[]}): FeatureCollection<LineString>;
208
```
209
210
[Spatial Analysis](./spatial-analysis.md)
211
212
### Line Processing
213
214
Specialized functions for working with LineString geometries including splitting, slicing, offsetting, and intersection operations.
215
216
```typescript { .api }
217
function lineSlice(startPt: Coord, stopPt: Coord, line: Feature<LineString> | LineString): Feature<LineString>;
218
function lineSliceAlong(line: Feature<LineString> | LineString, startDist: number, stopDist: number, options?: {units?: Units}): Feature<LineString>;
219
function lineSplit(line: FeatureCollection<LineString> | Feature<LineString> | LineString, splitter: FeatureCollection | Feature<any> | Geometry): FeatureCollection<LineString>;
220
function lineOffset(geojson: Feature<LineString | MultiLineString> | LineString | MultiLineString, distance: number, options?: {units?: Units}): FeatureCollection<LineString>;
221
function lineIntersect(line1: FeatureCollection | Feature<LineString | MultiLineString | Polygon | MultiPolygon> | LineString | MultiLineString | Polygon | MultiPolygon, line2: FeatureCollection | Feature<LineString | MultiLineString | Polygon | MultiPolygon> | LineString | MultiLineString | Polygon | MultiPolygon, options?: {removeDuplicates?: boolean}): FeatureCollection<Point>;
222
```
223
224
[Line Processing](./line-processing.md)
225
226
### Coordinate and Projection Operations
227
228
Functions for transforming coordinates, changing projections, and manipulating geometric positioning.
229
230
```typescript { .api }
231
function transformTranslate<G>(geojson: FeatureCollection<G> | Feature<G> | G, distance: number, direction: number, options?: {units?: Units; zTranslation?: number; mutate?: boolean}): FeatureCollection<G> | Feature<G>;
232
function transformRotate<G>(geojson: FeatureCollection<G> | Feature<G> | G, angle: number, options?: {pivot?: Coord; mutate?: boolean}): FeatureCollection<G> | Feature<G>;
233
function transformScale<G>(geojson: FeatureCollection<G> | Feature<G> | G, factor: number, options?: {origin?: string | Coord; mutate?: boolean}): FeatureCollection<G> | Feature<G>;
234
function toMercator<G>(geojson: G, options?: {mutate?: boolean}): G;
235
function toWgs84<G>(geojson: G, options?: {mutate?: boolean}): G;
236
```
237
238
[Coordinate Operations](./coordinate-operations.md)
239
240
### Advanced Spatial Analysis
241
242
Statistical analysis functions for spatial pattern detection, nearest neighbor analysis, spatial autocorrelation, and sophisticated geospatial analytics.
243
244
```typescript { .api }
245
function nearestNeighborAnalysis(dataset: FeatureCollection<Point>, options?: {studyArea?: Feature<Polygon> | Polygon | number; units?: Units}): NearestNeighborStatistics;
246
function quadratAnalysis(points: FeatureCollection<Point>, options?: {studyBbox?: BBox; quadratWidth?: number; quadratHeight?: number; units?: Units}): QuadratAnalysisResult;
247
function moranIndex(geojson: FeatureCollection<Polygon>, options?: {inputField: string; threshold?: number; p?: number}): {moranIndex: number; expectedMoranIndex: number; variance: number; zNorm: number};
248
function nearestPoint(targetPoint: Coord, points: FeatureCollection<Point>): Feature<Point>;
249
function standardDeviationalEllipse(points: FeatureCollection<Point>, options?: {weight?: string; steps?: number}): Feature<Polygon>;
250
```
251
252
[Advanced Analysis](./advanced-analysis.md)
253
254
### Data Utilities
255
256
Utility functions for manipulating, combining, and transforming GeoJSON data structures for spatial analysis and data preparation.
257
258
```typescript { .api }
259
function collect(polygons: FeatureCollection<Polygon | MultiPolygon>, points: FeatureCollection<Point>, inProperty: string, outProperty: string): FeatureCollection<Polygon | MultiPolygon>;
260
function tag(points: FeatureCollection<Point>, polygons: FeatureCollection<Polygon | MultiPolygon>, field: string, outField?: string): FeatureCollection<Point>;
261
function combine<G>(fc: FeatureCollection<G>): FeatureCollection<G>;
262
function explode(geojson: AllGeoJSON): FeatureCollection<Point>;
263
function flatten<G>(geojson: any): FeatureCollection<G>;
264
function clone<T>(geojson: T): T;
265
function cleanCoords<T>(geojson: T, options?: {mutate?: boolean}): T;
266
```
267
268
[Data Utilities](./data-utilities.md)
269
270
## Types
271
272
```typescript { .api }
273
// Core coordinate and unit types
274
type Coord = Feature<Point> | Point | Position;
275
type Units = "meters" | "metres" | "millimeters" | "millimetres" | "centimeters" | "centimetres" | "kilometers" | "kilometres" | "miles" | "nauticalmiles" | "inches" | "yards" | "feet" | "radians" | "degrees";
276
type AreaUnits = Exclude<Units, "radians" | "degrees"> | "acres" | "hectares";
277
type Grid = "point" | "square" | "hex" | "triangle";
278
type Corners = "sw" | "se" | "nw" | "ne" | "center" | "centroid";
279
type Lines = LineString | MultiLineString | Polygon | MultiPolygon;
280
type AllGeoJSON = Feature | FeatureCollection | Geometry | GeometryCollection;
281
type Id = string | number;
282
283
// Analysis result types
284
interface QuadratAnalysisResult {
285
criticalValue: number;
286
maxAbsoluteDifference: number;
287
isRandom: boolean;
288
observedDistribution: number[];
289
}
290
291
interface NearestNeighborStatistics {
292
units: Units & AreaUnits;
293
arealUnits: string;
294
observedMeanDistance: number;
295
expectedMeanDistance: number;
296
nearestNeighborIndex: number;
297
numberOfPoints: number;
298
zScore: number;
299
}
300
301
// Additional analysis types
302
interface StandardDeviationalEllipseResult {
303
centroid: Feature<Point>;
304
ellipse: Feature<Polygon>;
305
xStandardDistance: number;
306
yStandardDistance: number;
307
rotation: number;
308
}
309
310
// GeoJSON base types from @types/geojson
311
type Position = number[];
312
type BBox = [number, number, number, number] | [number, number, number, number, number, number];
313
type GeoJsonProperties = { [name: string]: any } | null;
314
```