spatialutils

The spatialutils class provides static utility functions for **performing geospatial operations** such as measurement, geometry manipulation, and spatial analysis.


1. Measurement Functions 📐

distance()
static distance(from: Coord, to: Coord, units?: string): number

Calculates the **distance** between two points (or feature centers) in the specified unit (e.g., 'kilometers', 'miles').

Returns: number (Distance)

Usage Example: Calculating Distance

const pt1 = [-75.343, 39.984] ;
const pt2 = [-75.534, 39.123] ;

const distKm = gtswebsdkgl.spatialutils.distance(pt1, pt2, {unites:'kilometers'});
console.log(`Distance: ${distKm.toFixed(2)} km`);
area()
static area(geojson: GeoJSON): number

Calculates the **area** of a Polygon or MultiPolygon geometry in square meters.

Returns: number (Area in square meters)

Usage Example: Calculating Polygon Area

const poly ={ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] };
const areaSqMeters = gtswebsdkgl.spatialutils.area(poly);
console.log(`Area: ${areaSqMeters.toLocaleString()} sq meters`);
length()
static length(geojson: GeoJSON, units?: string): number

Takes a GeoJSON and measures its length in the specified units, (Multi)Point's distance are ignored.

Returns: number (Length)

Usage Example: Calculating Line Length

const line ={ "type": "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ] };
const lineMiles = gtswebsdkgl.spatialutils.length(line, {unites:'kilometers'});
console.log(`Length: ${lineMiles.toFixed(2)} miles`);
bearing()
static bearing(from: GeoJSON, to: GeoJSON): number

Calculates the **bearing** (direction) from one Point to another in degrees, ranging from -180 to 180.

Returns: number (Bearing in degrees)

Usage Example: Getting Bearing

const ptA = { type: 'Point', coordinates: [ -70, 40 ] };
const ptB = { type: 'Point', coordinates: [ -75, 45 ] };

const b = gtswebsdkgl.spatialutils.bearing(ptA, ptB);
console.log(`Bearing from A to B: ${b.toFixed(2)} degrees`);

2. Transformation & Derivation Functions 🔨

bbox()
static bbox(geojson: GeoJSON): Array<number>

Calculates the **bounding box** (BBOX) of any GeoJSON object in the format [minX, minY, maxX, maxY].

Returns: Array<number> (BBOX array)

Usage Example: Getting the BBOX

const line = { type: 'LineString', coordinates: [[10, 0], [0, 10]] };
const box = gtswebsdkgl.spatialutils.bbox(line);
console.log(`BBOX: [${box.join(', ')}]`); // Output: BBOX: [0, 0, 10, 10]
bboxPolygon()
static bboxPolygon(bbox: Array<number>): GeoJSON

Takes a BBOX array and returns a GeoJSON **Polygon Feature** that represents that bounding box.

Returns: GeoJSON (Polygon Feature)

Usage Example: Creating a Polygon from a BBOX

const bboxArray = [ -75, 40, -70, 45 ];
const bboxPoly = gtswebsdkgl.spatialutils.bboxPolygon(bboxArray);
console.log(bboxPoly.geometry.type); // Output: 'Polygon'
envelope()
static envelope(geojson: GeoJSON): GeoJSON

Calculates the **minimal bounding rectangle** (same as BBOX Polygon) for a given GeoJSON object.

Returns: GeoJSON (Polygon Feature)

Usage Example: Creating a Bounding Envelope

const points = { /* FeatureCollection of Points */ };
const envelopePoly = gtswebsdkgl.spatialutils.envelope(points);
console.log(envelopePoly.properties); // Should be { bbox: [...] }
convex()
static convex(geojson: GeoJSON): GeoJSON | null

Calculates the **Convex Hull** (smallest convex polygon) of a Point, MultiPoint, or FeatureCollection of any type.

Returns: GeoJSON | null (Polygon Feature or null)

Usage Example: Calculating Convex Hull

const points = { /* FeatureCollection of Points */ };
const hull = gtswebsdkgl.spatialutils.convex(points);
console.log(hull.geometry.type); // Output: 'Polygon'
concave()
static concave(geojson: GeoJSON, maxEdge: number, units?: string): GeoJSON | null

Calculates the **Concave Hull** of a set of points. Requires a maxEdge distance constraint.

Returns: GeoJSON | null (Polygon Feature or null)

Usage Example: Calculating Concave Hull

const points = { /* FeatureCollection of Points */ };
// Max edge length of 10 kilometers
const concaveHull = gtswebsdkgl.spatialutils.concave(points, 10, 'kilometers');
console.log(concaveHull.geometry.type);

3. Center & Point Location Functions 🎯

centroid()
static centroid(geojson: GeoJSON): GeoJSON

Calculates the **centroid** (center of geometry) of a GeoJSON feature using the mathematical center of its coordinates.

Returns: GeoJSON (Point Feature)

Usage Example: Getting the Centroid

const poly = { /* GeoJSON Polygon Feature */ };
const c = gtswebsdkgl.spatialutils.centroid(poly);
console.log('Centroid:', c.geometry.coordinates);
center()
static center(geojson: GeoJSON): GeoJSON

Calculates the **center** of a GeoJSON feature based on the midpoint of its bounding box (BBOX).

Returns: GeoJSON (Point Feature)

Usage Example: Getting the BBOX Center

const features = { /* GeoJSON FeatureCollection */ };
const center = gtswebsdkgl.spatialutils.center(features);
console.log('BBOX Center:', center.geometry.coordinates);
centerOfMass()
static centerOfMass(geojson: GeoJSON): GeoJSON

Calculates the **center of mass** (weighted center) for a GeoJSON feature. Typically more representative of the visual center for polygons than `centroid`.

Returns: GeoJSON (Point Feature)

Usage Example: Finding the Center of Mass

const polygon = { /* GeoJSON Polygon Feature */ };
const massCenter = gtswebsdkgl.spatialutils.centerOfMass(polygon);
console.log('Center of Mass:', massCenter.geometry.coordinates);
along()
static along(line: GeoJSON, distance: number, units?: string): GeoJSON

Returns a **Point** at a specified **distance** along a LineString.

Returns: GeoJSON (Point Feature)

Usage Example: Point Along Line

const line = { /* GeoJSON LineString feature */ };
const ptAlong = gtswebsdkgl.spatialutils.along(line, 5, 'miles');
console.log('Point 5 miles along:', ptAlong.geometry.coordinates);
midpoint()
static midpoint(point1: GeoJSON, point2: GeoJSON): GeoJSON

Calculates the **midpoint** of the straight line segment between two given points.

Returns: GeoJSON (Point Feature)

Usage Example: Finding the Midpoint

const start = { type: 'Point', coordinates: [ 0, 0 ] };
const end = { type: 'Point', coordinates: [ 10, 10 ] };

const mid = gtswebsdkgl.spatialutils.midpoint(start, end);
console.log('Midpoint:', mid.geometry.coordinates); // Output: [5, 5]
pointOnFeature()
static pointOnFeature(geojson: GeoJSON): GeoJSON

Returns a **Point** that is guaranteed to be **inside** a given Polygon or MultiPolygon Feature.

Returns: GeoJSON (Point Feature)

Usage Example: Guaranteed Point Inside

const complexPoly = { /* Polygon with holes */ };
const innerPoint = gtswebsdkgl.spatialutils.pointOnFeature(complexPoly);
// This point is guaranteed to be usable for labelling or positioning

4. Boolean & Spatial Analysis Functions 🧠

booleanPointInPolygon()
static booleanPointInPolygon(point: GeoJSON, polygon: GeoJSON, ignoreBoundary?: boolean): boolean

Checks if a **Point is inside a Polygon**. Returns true if it is, false otherwise.

Returns: boolean

Usage Example: Checking Point Inclusion

const pt = { type: 'Point', coordinates: [ 10, 10 ] };
const poly = { /* GeoJSON Polygon covering [0,0] to [20,20] */ };

const isInside = gtswebsdkgl.spatialutils.booleanPointInPolygon(pt, poly);
console.log('Point is inside:', isInside);
booleanWithin()
static booleanWithin(feature1: GeoJSON, feature2: GeoJSON): boolean

Checks if **feature1 is completely within feature2** (e.g., Point in Polygon, LineString in Polygon).

Returns: boolean

Usage Example: Feature Within

const smallLine = { /* Line inside a city boundary */ };
const cityBoundary = { /* City Polygon */ };

const isContained = gtswebsdkgl.spatialutils.booleanWithin(smallLine, cityBoundary);
console.log('Line is within boundary:', isContained);
booleanContains()
static booleanContains(feature1: GeoJSON, feature2: GeoJSON): boolean

Checks if **feature1 completely contains feature2**. (Inverse of `booleanWithin`).

Returns: boolean

Usage Example: Feature Contains

const bigPoly = { /* Large Polygon A */ };
const smallPoly = { /* Small Polygon B */ };

const contains = gtswebsdkgl.spatialutils.booleanContains(bigPoly, smallPoly);
console.log('A contains B:', contains);
booleanOverlap()
static booleanOverlap(feature1: GeoJSON, feature2: GeoJSON): boolean

Checks if the intersection of two geometries is not empty and is not equal to either of the features.

Returns: boolean

Usage Example: Checking for Partial Overlap

const poly1 = { /* Polygon 1 */ };
const poly2 = { /* Polygon 2 */ };

const overlaps = gtswebsdkgl.spatialutils.booleanOverlap(poly1, poly2);
console.log('Polygons partially overlap:', overlaps);
booleanCrosses()
static booleanCrosses(feature1: GeoJSON, feature2: GeoJSON): boolean

Checks if two geometries **cross** (e.g., a LineString crosses a Polygon boundary, or two LineStrings intersect internally).

Returns: boolean

Usage Example: Checking if Lines Cross

const lineA = { /* LineString A */ };
const lineB = { /* LineString B */ };

const crosses = gtswebsdkgl.spatialutils.booleanCrosses(lineA, lineB);
console.log('Lines cross:', crosses);
booleanDisjoint()
static booleanDisjoint(feature1: GeoJSON, feature2: GeoJSON): boolean

Checks if two geometries have **no points in common** (they do not intersect or touch).

Returns: boolean

Usage Example: Checking for No Intersection

const region1 = { /* Polygon far North */ };
const region2 = { /* Polygon far South */ };

const disjoint = gtswebsdkgl.spatialutils.booleanDisjoint(region1, region2);
console.log('Regions are separate:', disjoint); // Output: true
nearestPoint()
static nearestPoint(targetPoint: GeoJSON, points: GeoJSON): GeoJSON

Takes a reference point and a collection of points, and returns the **nearest point** feature from the collection.

Returns: GeoJSON (Point Feature)

Usage Example: Finding Nearest Point

const target = { type: 'Point', coordinates: [ 5, 5 ] };
const candidates = { /* FeatureCollection of points */ };

const nearest = gtswebsdkgl.spatialutils.nearestPoint(target, candidates);
console.log('Nearest candidate:', nearest.geometry.coordinates);
nearestPointOnLine()
static nearestPointOnLine(line: GeoJSON, point: GeoJSON): GeoJSON

Returns the **closest Point on a LineString** to a given reference Point.

Returns: GeoJSON (Point Feature)

Usage Example: Point Projection

const road = { /* LineString of a road */ };
const location = { /* Point off the road */ };

const projected = gtswebsdkgl.spatialutils.nearestPointOnLine(road, location);
console.log('Closest point on road:', projected.geometry.coordinates);
pointsWithinPolygon()
static pointsWithinPolygon(points: GeoJSON, polygon: GeoJSON): GeoJSON

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

Returns: GeoJSON (FeatureCollection)

Usage Example: Points in Area of Interest

const allSites = { /* FeatureCollection of sites */ };
const aoi = { /* Polygon defining area of interest */ };

const filteredSites = gtswebsdkgl.spatialutils.pointsWithinPolygon(allSites, aoi);
console.log(`Found ${filteredSites.features.length} sites inside AOI.`);

5. Geometry Processing & Set Operations 🔄

union()
static union(feature1: GeoJSON, feature2: GeoJSON): GeoJSON

Merges two or more Polygon or MultiPolygon features into a single feature. Uses a **spatial union** operation.

Returns: GeoJSON (Polygon Feature)

Usage Example: Combining Polygons

const plotA = { /* Polygon A */ };
const plotB = { /* Polygon B */ };

const mergedPlot = gtswebsdkgl.spatialutils.union(plotA, plotB);
console.log('Resulting geometry type:', mergedPlot.geometry.type);
intersect()
static intersect(feature1: GeoJSON, feature2: GeoJSON): GeoJSON | null

Calculates the **geometric intersection** of two features (the area/line/point shared by both).

Returns: GeoJSON | null (The resulting geometry or null)

Usage Example: Finding Overlapping Area

const polyA = { /* GeoJSON Polygon A */ };
const polyB = { /* GeoJSON Polygon B */ };

const intersection = gtswebsdkgl.spatialutils.intersect(polyA, polyB);
if (intersection) {
  console.log('Intersection area found:', gtswebsdkgl.spatialutils.area(intersection));
}
difference()
static difference(feature1: GeoJSON, feature2: GeoJSON): GeoJSON | null

Calculates the **geometric difference** (the area of feature1 that does not overlap feature2).

Returns: GeoJSON | null (The resulting geometry or null)

Usage Example: Cutting a Hole

const bigPoly = { /* Large outer Polygon */ };
const smallPoly = { /* Small inner Polygon to cut out */ };

const remainder = gtswebsdkgl.spatialutils.difference(bigPoly, smallPoly);
console.log('Remaining shape type:', remainder.geometry.type);
simplify()
static simplify(geojson: GeoJSON, tolerance: number): GeoJSON

Simplifies a LineString or Polygon geometry using the **Douglas-Peucker algorithm**, reducing the number of vertices.

Returns: GeoJSON (Simplified Feature)

Usage Example: Simplifying a Line

const noisyLine = { /* Detailed LineString */ };
// Simplify with a tolerance of 0.01 degrees
const simpleLine = gtswebsdkgl.spatialutils.simplify(noisyLine, 0.01);
console.log('Original points vs simplified points');
polygonToLine()
static polygonToLine(polygon: GeoJSON): GeoJSON

Converts a Polygon or MultiPolygon feature into a **LineString** or **MultiLineString** feature that traces its exterior and interior rings.

Returns: GeoJSON (LineString Feature)

Usage Example: Polygon to Line

const poly = { /* GeoJSON Polygon */ };
const line = gtswebsdkgl.spatialutils.polygonToLine(poly);
console.log('New geometry type:', line.geometry.type); // Output: 'LineString'
lineToPolygon()
static lineToPolygon(line: GeoJSON): GeoJSON

Converts a LineString feature into a **Polygon** feature. Requires the LineString to be a closed loop (start/end points match).

Returns: GeoJSON (Polygon Feature)

Usage Example: Line to Polygon

const closedLine = { /* LineString where start=end */ };
const poly = gtswebsdkgl.spatialutils.lineToPolygon(closedLine);
console.log('New geometry type:', poly.geometry.type); // Output: 'Polygon'
collect()
static collect(polygons: GeoJSON, points: GeoJSON, attribute: string, outAttribute: string): GeoJSON

Aggregates properties from a Point FeatureCollection into a Polygon FeatureCollection based on spatial inclusion.

Returns: GeoJSON (Polygon FeatureCollection with aggregated data)

Usage Example: Aggregating Data

const zones = { /* Polygons with attribute 'name' */ };
const sales = { /* Points with attribute 'revenue' */ };

const results = gtswebsdkgl.spatialutils.collect(zones, sales, 'revenue', 'total_revenue');
// Zones now contain a 'total_revenue' property

6. Line Manipulation & Grid Functions 📏

lineSlice()
static lineSlice(startPoint: GeoJSON, endPoint: GeoJSON, line: GeoJSON): GeoJSON

Returns a segment of a LineString sliced between the two nearest points to the given start and end coordinates.

Returns: GeoJSON (LineString Feature)

Usage Example: Slicing a Line

const route = { /* Long LineString */ };
const start = { /* Point near the start */ };
const end = { /* Point near the end */ };

const segment = gtswebsdkgl.spatialutils.lineSlice(start, end, route);
console.log('Segment length:', gtswebsdkgl.spatialutils.length(segment));
lineSliceAlong()
static lineSliceAlong(line: GeoJSON, startDistance: number, endDistance: number, units?: string): GeoJSON

Returns a segment of a LineString sliced between two distances along the line.

Returns: GeoJSON (LineString Feature)

Usage Example: Slicing by Distance

const route = { /* Long LineString */ };
// Get segment between 10km and 20km along the route
const section = gtswebsdkgl.spatialutils.lineSliceAlong(route, 10, 20, {units:'kilometers'});
console.log('Section length:', gtswebsdkgl.spatialutils.length(section, {units:'kilometers'}));
lineChunk()
static lineChunk(line: GeoJSON, segmentLength: number, units?: string): GeoJSON

Divides a LineString into **smaller segments** of a specified length, returning a MultiLineString or FeatureCollection.

Returns: GeoJSON (MultiLineString Feature)

Usage Example: Splitting a Line

const routeLine = { /* GeoJSON LineString */ };
// Chunk the line into 5-mile segments
const segments = gtswebsdkgl.spatialutils.lineChunk(routeLine, 5, {units:'miles'});
console.log(`Split route into ${segments.features.length} features.`);
interpolate()
static interpolate(line: GeoJSON, distance: number, units?: string): GeoJSON

Returns a **Point** at a specified distance along a LineString, similar to `along`.

Returns: GeoJSON (Point Feature)

Usage Example: Interpolate (same as along)

const line = { /* GeoJSON LineString feature */ };
const pt = gtswebsdkgl.spatialutils.interpolate(line, 2.5, {units:'miles'});
console.log('Point 2.5 miles along:', pt.geometry.coordinates);
pointGrid()
static pointGrid(bbox: Array<number>, cellSize: number, units?: string): GeoJSON

Creates a **FeatureCollection of Points** at regular intervals across a defined BBOX.

Returns: GeoJSON (Point FeatureCollection)

Usage Example: Creating a Point Grid

const bbox = [ -70, 40, -60, 50 ];
// 10km cell size
const grid = gtswebsdkgl.spatialutils.pointGrid(bbox, 10, {units:'kilometers'});
console.log(`Generated ${grid.features.length} points.`);
hexGrid()
static hexGrid(bbox: Array<number>, cellSize: number, units?: string): GeoJSON

Creates a **FeatureCollection of hexagonal Polygons** at a uniform size across a defined BBOX.

Returns: GeoJSON (Polygon FeatureCollection)

Usage Example: Creating a Hex Grid

const bbox = [ -70, 40, -60, 50 ];
// 5-mile cell size
const hexes = gtswebsdkgl.spatialutils.hexGrid(bbox, 5, {units:'miles'});
console.log(`Generated ${hexes.features.length} hexagonal cells.`);
triangleGrid()
static triangleGrid(bbox: Array<number>, cellSize: number, units?: string): GeoJSON

Creates a **FeatureCollection of triangular Polygons** at a uniform size across a defined BBOX.

Returns: GeoJSON (Polygon FeatureCollection)

Usage Example: Creating a Triangle Grid

const bbox = [ -70, 40, -60, 50 ];
// 10km cell size
const triangles = gtswebsdkgl.spatialutils.triangleGrid(bbox, 10, {units:'kilometers'});
console.log(`Generated ${triangles.features.length} triangular cells.`);