CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-turf--turf

A JavaScript library for performing geospatial operations with GeoJSON data

Pending
Overview
Eval results
Files

data-utilities.mddocs/

Data Utilities

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

Capabilities

Data Collection and Aggregation

Collect and aggregate properties from spatial relationships.

/**
 * Collects all the property values from points that fall within polygons in a FeatureCollection,
 * then adds the collected values as a property to each polygon feature.
 */
function collect(
  polygons: FeatureCollection<Polygon | MultiPolygon>,
  points: FeatureCollection<Point>,
  inProperty: string,
  outProperty: string
): FeatureCollection<Polygon | MultiPolygon>;

/**
 * Takes a set of points and a set of polygons and performs a spatial join.
 * Points that fall within polygons get the polygon's properties.
 */
function tag(
  points: FeatureCollection<Point>,
  polygons: FeatureCollection<Polygon | MultiPolygon>,
  field: string,
  outField?: string
): FeatureCollection<Point>;

Usage Examples:

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

// Create test data
const polygons = randomPolygon(5, { bbox: [0, 0, 10, 10] });
const points = randomPoint(50, { bbox: [0, 0, 10, 10] });

// Add properties to points
points.features.forEach((point, i) => {
  point.properties = { value: i, category: i % 3 };
});

// Add properties to polygons
polygons.features.forEach((polygon, i) => {
  polygon.properties = { zone: `Zone_${i}`, type: 'residential' };
});

// Collect point values within polygons
const collected = collect(polygons, points, 'value', 'collected_values');
console.log('Collected point values in each polygon');

// Tag points with polygon properties
const tagged = tag(points, polygons, 'zone', 'polygon_zone');
console.log('Points tagged with polygon zone information');

Geometry Combination and Separation

Combine multiple geometries or separate complex geometries into simpler parts.

/**
 * Combines a FeatureCollection of Point, LineString, or Polygon features
 * into MultiPoint, MultiLineString, or MultiPolygon features.
 */
function combine<G>(fc: FeatureCollection<G>): FeatureCollection<G>;

/**
 * Takes a feature or set of features and returns all positions as points.
 */
function explode(geojson: AllGeoJSON): FeatureCollection<Point>;

/**
 * Flattens any GeoJSON to a FeatureCollection of simple, non-complex geometries.
 * Multi* geometries are split into individual features.
 */
function flatten<G>(geojson: any): FeatureCollection<G>;

Usage Examples:

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

// Create individual features
const points = featureCollection([
  point([0, 0], { id: 1 }),
  point([1, 1], { id: 2 }),
  point([2, 2], { id: 3 })
]);

// Combine into MultiPoint
const combined = combine(points);
console.log('Combined features:', combined.features.length);

// Explode linestring to points
const line = lineString([[0, 0], [1, 1], [2, 2]]);
const exploded = explode(line);
console.log('Exploded points:', exploded.features.length);

// Flatten complex geometries
const flattened = flatten(combined);
console.log('Flattened features:', flattened.features.length);

Data Cloning and Copying

Create deep copies of GeoJSON objects.

/**
 * Returns a cloned copy of the passed GeoJSON Object, including possible 'Foreign Members'.
 */
function clone<T>(geojson: T): T;

/**
 * Clones the properties of a GeoJSON feature.
 */
function cloneProperties(properties: GeoJsonProperties): GeoJsonProperties;

Usage Examples:

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

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

// Clone the entire feature
const clonedPoint = clone(originalPoint);
clonedPoint.properties!.name = 'modified';

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

// Clone just properties
const originalProps = { name: 'test', value: 42, nested: { data: 'important' } };
const clonedProps = cloneProperties(originalProps);
clonedProps.nested.data = 'changed';

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

Coordinate Cleaning and Optimization

Clean and optimize coordinate arrays.

/**
 * Removes redundant coordinates from any GeoJSON Geometry.
 */
function cleanCoords<T>(geojson: T, options?: { mutate?: boolean }): T;

/**
 * Takes a GeoJSON Feature or FeatureCollection and truncates the precision of the geometry.
 */
function truncate<T>(
  geojson: T,
  options?: {
    precision?: number;
    coordinates?: number;
    mutate?: boolean;
  }
): T;

Usage Examples:

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

// Create line with redundant coordinates
const redundantLine = lineString([
  [0, 0], [0, 0], [1, 1], [1, 1], [2, 2]
]);

// Clean redundant coordinates
const cleanedLine = cleanCoords(redundantLine);
console.log('Original coords:', redundantLine.geometry.coordinates.length);
console.log('Cleaned coords:', cleanedLine.geometry.coordinates.length);

// Create high-precision coordinates
const preciseLine = lineString([
  [0.123456789, 0.987654321],
  [1.111111111, 1.222222222]
]);

// Truncate precision to 4 decimal places
const truncatedLine = truncate(preciseLine, { precision: 4 });
console.log('Original:', preciseLine.geometry.coordinates);
console.log('Truncated:', truncatedLine.geometry.coordinates);

Coordinate Transformation

Transform and manipulate coordinate positions.

/**
 * Flips the coordinates of any GeoJSON geometry.
 */
function flip<T>(geojson: T, options?: { mutate?: boolean }): T;

/**
 * Rewinds the coordinates of a GeoJSON geometry in clockwise or counter-clockwise direction.
 */
function rewind<T>(
  geojson: T,
  options?: { reverse?: boolean; mutate?: boolean }
): T;

Usage Examples:

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

// Create polygon with [longitude, latitude] coordinates
const poly = polygon([[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]]);

// Flip coordinates from [lon, lat] to [lat, lon]
const flipped = flip(poly);
console.log('Original:', poly.geometry.coordinates[0][0]);
console.log('Flipped:', flipped.geometry.coordinates[0][0]);

// Rewind polygon coordinates
const rewound = rewind(poly, { reverse: true });
console.log('Coordinates rewound in reverse direction');

Envelope and Bounding Operations

Create bounding geometries and envelopes.

/**
 * Takes any number of features and returns a rectangular Polygon that encompasses all vertices.
 */
function envelope(geojson: AllGeoJSON): Feature<Polygon>;

/**
 * Takes a bbox and returns an equivalent polygon.
 */
function bboxPolygon(bbox: BBox, options?: { properties?: GeoJsonProperties; id?: Id }): Feature<Polygon>;

/**
 * Clips any GeoJSON Geometry or Feature with a rectangular bounding box.
 */
function bboxClip<T>(
  feature: Feature<T> | T,
  bbox: BBox
): Feature<T> | FeatureCollection<T>;

Usage Examples:

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

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

// Create envelope around all features
const env = envelope(features);
console.log('Envelope created around all points');

// Get bounding box and create polygon
const bounds = bbox(features);
const boundsPoly = bboxPolygon(bounds, { properties: { type: 'bounds' } });

// Clip features to smaller area
const clipBounds = [1, 1, 3, 3] as BBox;
const clipped = bboxClip(features, clipBounds);
console.log('Features clipped to smaller area');

Sampling and Selection

Sample points and select features based on spatial criteria.

/**
 * Takes a Feature or FeatureCollection and returns a subset.
 */
function sample<G>(
  featurecollection: FeatureCollection<G>,
  num: number
): FeatureCollection<G>;

/**
 * Takes a set of points and a set of polygons and returns the points that fall within the polygons.
 */
function pointsWithinPolygon(
  points: FeatureCollection<Point> | Feature<Point>,
  polygons: FeatureCollection<Polygon | MultiPolygon> | Feature<Polygon | MultiPolygon> | Polygon | MultiPolygon
): FeatureCollection<Point>;

Usage Examples:

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

// Create test data
const allPoints = randomPoint(100, { bbox: [0, 0, 10, 10] });
const polygons = randomPolygon(3, { bbox: [2, 2, 8, 8] });

// Sample 20 random points
const sampledPoints = sample(allPoints, 20);
console.log(`Sampled ${sampledPoints.features.length} points from ${allPoints.features.length}`);

// Find points within polygons
const pointsInside = pointsWithinPolygon(allPoints, polygons);
console.log(`Found ${pointsInside.features.length} points inside polygons`);

Install with Tessl CLI

npx tessl i tessl/npm-turf--turf

docs

advanced-analysis.md

boolean-operations.md

coordinate-operations.md

data-generation.md

data-utilities.md

geometric-operations.md

helpers.md

index.md

invariant.md

line-processing.md

measurement.md

meta.md

spatial-analysis.md

tile.json