or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-analysis.mdboolean-operations.mdcoordinate-operations.mddata-generation.mddata-utilities.mdgeometric-operations.mdhelpers.mdindex.mdinvariant.mdline-processing.mdmeasurement.mdmeta.mdspatial-analysis.md

data-utilities.mddocs/

0

# Data Utilities

1

2

Utility functions for manipulating, combining, and transforming GeoJSON data structures. These functions help with data preparation, cleaning, and organization for spatial analysis.

3

4

## Capabilities

5

6

### Data Collection and Aggregation

7

8

Collect and aggregate properties from spatial relationships.

9

10

```typescript { .api }

11

/**

12

* Collects all the property values from points that fall within polygons in a FeatureCollection,

13

* then adds the collected values as a property to each polygon feature.

14

*/

15

function collect(

16

polygons: FeatureCollection<Polygon | MultiPolygon>,

17

points: FeatureCollection<Point>,

18

inProperty: string,

19

outProperty: string

20

): FeatureCollection<Polygon | MultiPolygon>;

21

22

/**

23

* Takes a set of points and a set of polygons and performs a spatial join.

24

* Points that fall within polygons get the polygon's properties.

25

*/

26

function tag(

27

points: FeatureCollection<Point>,

28

polygons: FeatureCollection<Polygon | MultiPolygon>,

29

field: string,

30

outField?: string

31

): FeatureCollection<Point>;

32

```

33

34

**Usage Examples:**

35

36

```typescript

37

import { collect, tag, randomPoint, randomPolygon } from "@turf/turf";

38

39

// Create test data

40

const polygons = randomPolygon(5, { bbox: [0, 0, 10, 10] });

41

const points = randomPoint(50, { bbox: [0, 0, 10, 10] });

42

43

// Add properties to points

44

points.features.forEach((point, i) => {

45

point.properties = { value: i, category: i % 3 };

46

});

47

48

// Add properties to polygons

49

polygons.features.forEach((polygon, i) => {

50

polygon.properties = { zone: `Zone_${i}`, type: 'residential' };

51

});

52

53

// Collect point values within polygons

54

const collected = collect(polygons, points, 'value', 'collected_values');

55

console.log('Collected point values in each polygon');

56

57

// Tag points with polygon properties

58

const tagged = tag(points, polygons, 'zone', 'polygon_zone');

59

console.log('Points tagged with polygon zone information');

60

```

61

62

### Geometry Combination and Separation

63

64

Combine multiple geometries or separate complex geometries into simpler parts.

65

66

```typescript { .api }

67

/**

68

* Combines a FeatureCollection of Point, LineString, or Polygon features

69

* into MultiPoint, MultiLineString, or MultiPolygon features.

70

*/

71

function combine<G>(fc: FeatureCollection<G>): FeatureCollection<G>;

72

73

/**

74

* Takes a feature or set of features and returns all positions as points.

75

*/

76

function explode(geojson: AllGeoJSON): FeatureCollection<Point>;

77

78

/**

79

* Flattens any GeoJSON to a FeatureCollection of simple, non-complex geometries.

80

* Multi* geometries are split into individual features.

81

*/

82

function flatten<G>(geojson: any): FeatureCollection<G>;

83

```

84

85

**Usage Examples:**

86

87

```typescript

88

import { combine, explode, flatten, featureCollection, point, lineString } from "@turf/turf";

89

90

// Create individual features

91

const points = featureCollection([

92

point([0, 0], { id: 1 }),

93

point([1, 1], { id: 2 }),

94

point([2, 2], { id: 3 })

95

]);

96

97

// Combine into MultiPoint

98

const combined = combine(points);

99

console.log('Combined features:', combined.features.length);

100

101

// Explode linestring to points

102

const line = lineString([[0, 0], [1, 1], [2, 2]]);

103

const exploded = explode(line);

104

console.log('Exploded points:', exploded.features.length);

105

106

// Flatten complex geometries

107

const flattened = flatten(combined);

108

console.log('Flattened features:', flattened.features.length);

109

```

110

111

### Data Cloning and Copying

112

113

Create deep copies of GeoJSON objects.

114

115

```typescript { .api }

116

/**

117

* Returns a cloned copy of the passed GeoJSON Object, including possible 'Foreign Members'.

118

*/

119

function clone<T>(geojson: T): T;

120

121

/**

122

* Clones the properties of a GeoJSON feature.

123

*/

124

function cloneProperties(properties: GeoJsonProperties): GeoJsonProperties;

125

```

126

127

**Usage Examples:**

128

129

```typescript

130

import { clone, cloneProperties, point } from "@turf/turf";

131

132

const originalPoint = point([1, 2], { name: 'test', value: 42 });

133

134

// Clone the entire feature

135

const clonedPoint = clone(originalPoint);

136

clonedPoint.properties!.name = 'modified';

137

138

console.log('Original name:', originalPoint.properties?.name); // 'test'

139

console.log('Cloned name:', clonedPoint.properties?.name); // 'modified'

140

141

// Clone just properties

142

const originalProps = { name: 'test', value: 42, nested: { data: 'important' } };

143

const clonedProps = cloneProperties(originalProps);

144

clonedProps.nested.data = 'changed';

145

146

console.log('Original nested data:', originalProps.nested.data); // 'important'

147

console.log('Cloned nested data:', clonedProps.nested.data); // 'changed'

148

```

149

150

### Coordinate Cleaning and Optimization

151

152

Clean and optimize coordinate arrays.

153

154

```typescript { .api }

155

/**

156

* Removes redundant coordinates from any GeoJSON Geometry.

157

*/

158

function cleanCoords<T>(geojson: T, options?: { mutate?: boolean }): T;

159

160

/**

161

* Takes a GeoJSON Feature or FeatureCollection and truncates the precision of the geometry.

162

*/

163

function truncate<T>(

164

geojson: T,

165

options?: {

166

precision?: number;

167

coordinates?: number;

168

mutate?: boolean;

169

}

170

): T;

171

```

172

173

**Usage Examples:**

174

175

```typescript

176

import { cleanCoords, truncate, lineString } from "@turf/turf";

177

178

// Create line with redundant coordinates

179

const redundantLine = lineString([

180

[0, 0], [0, 0], [1, 1], [1, 1], [2, 2]

181

]);

182

183

// Clean redundant coordinates

184

const cleanedLine = cleanCoords(redundantLine);

185

console.log('Original coords:', redundantLine.geometry.coordinates.length);

186

console.log('Cleaned coords:', cleanedLine.geometry.coordinates.length);

187

188

// Create high-precision coordinates

189

const preciseLine = lineString([

190

[0.123456789, 0.987654321],

191

[1.111111111, 1.222222222]

192

]);

193

194

// Truncate precision to 4 decimal places

195

const truncatedLine = truncate(preciseLine, { precision: 4 });

196

console.log('Original:', preciseLine.geometry.coordinates);

197

console.log('Truncated:', truncatedLine.geometry.coordinates);

198

```

199

200

### Coordinate Transformation

201

202

Transform and manipulate coordinate positions.

203

204

```typescript { .api }

205

/**

206

* Flips the coordinates of any GeoJSON geometry.

207

*/

208

function flip<T>(geojson: T, options?: { mutate?: boolean }): T;

209

210

/**

211

* Rewinds the coordinates of a GeoJSON geometry in clockwise or counter-clockwise direction.

212

*/

213

function rewind<T>(

214

geojson: T,

215

options?: { reverse?: boolean; mutate?: boolean }

216

): T;

217

```

218

219

**Usage Examples:**

220

221

```typescript

222

import { flip, rewind, polygon } from "@turf/turf";

223

224

// Create polygon with [longitude, latitude] coordinates

225

const poly = polygon([[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]]);

226

227

// Flip coordinates from [lon, lat] to [lat, lon]

228

const flipped = flip(poly);

229

console.log('Original:', poly.geometry.coordinates[0][0]);

230

console.log('Flipped:', flipped.geometry.coordinates[0][0]);

231

232

// Rewind polygon coordinates

233

const rewound = rewind(poly, { reverse: true });

234

console.log('Coordinates rewound in reverse direction');

235

```

236

237

### Envelope and Bounding Operations

238

239

Create bounding geometries and envelopes.

240

241

```typescript { .api }

242

/**

243

* Takes any number of features and returns a rectangular Polygon that encompasses all vertices.

244

*/

245

function envelope(geojson: AllGeoJSON): Feature<Polygon>;

246

247

/**

248

* Takes a bbox and returns an equivalent polygon.

249

*/

250

function bboxPolygon(bbox: BBox, options?: { properties?: GeoJsonProperties; id?: Id }): Feature<Polygon>;

251

252

/**

253

* Clips any GeoJSON Geometry or Feature with a rectangular bounding box.

254

*/

255

function bboxClip<T>(

256

feature: Feature<T> | T,

257

bbox: BBox

258

): Feature<T> | FeatureCollection<T>;

259

```

260

261

**Usage Examples:**

262

263

```typescript

264

import { envelope, bboxPolygon, bboxClip, bbox, randomPoint } from "@turf/turf";

265

266

// Create some random features

267

const features = randomPoint(10, { bbox: [0, 0, 5, 5] });

268

269

// Create envelope around all features

270

const env = envelope(features);

271

console.log('Envelope created around all points');

272

273

// Get bounding box and create polygon

274

const bounds = bbox(features);

275

const boundsPoly = bboxPolygon(bounds, { properties: { type: 'bounds' } });

276

277

// Clip features to smaller area

278

const clipBounds = [1, 1, 3, 3] as BBox;

279

const clipped = bboxClip(features, clipBounds);

280

console.log('Features clipped to smaller area');

281

```

282

283

### Sampling and Selection

284

285

Sample points and select features based on spatial criteria.

286

287

```typescript { .api }

288

/**

289

* Takes a Feature or FeatureCollection and returns a subset.

290

*/

291

function sample<G>(

292

featurecollection: FeatureCollection<G>,

293

num: number

294

): FeatureCollection<G>;

295

296

/**

297

* Takes a set of points and a set of polygons and returns the points that fall within the polygons.

298

*/

299

function pointsWithinPolygon(

300

points: FeatureCollection<Point> | Feature<Point>,

301

polygons: FeatureCollection<Polygon | MultiPolygon> | Feature<Polygon | MultiPolygon> | Polygon | MultiPolygon

302

): FeatureCollection<Point>;

303

```

304

305

**Usage Examples:**

306

307

```typescript

308

import { sample, pointsWithinPolygon, randomPoint, randomPolygon } from "@turf/turf";

309

310

// Create test data

311

const allPoints = randomPoint(100, { bbox: [0, 0, 10, 10] });

312

const polygons = randomPolygon(3, { bbox: [2, 2, 8, 8] });

313

314

// Sample 20 random points

315

const sampledPoints = sample(allPoints, 20);

316

console.log(`Sampled ${sampledPoints.features.length} points from ${allPoints.features.length}`);

317

318

// Find points within polygons

319

const pointsInside = pointsWithinPolygon(allPoints, polygons);

320

console.log(`Found ${pointsInside.features.length} points inside polygons`);

321

```