A JavaScript library for performing geospatial operations with GeoJSON data
—
Advanced statistical analysis functions for spatial pattern detection, nearest neighbor analysis, spatial autocorrelation, and other sophisticated geospatial analytics.
Comprehensive nearest neighbor statistical analysis for spatial distribution patterns.
/**
* Nearest neighbor analysis measures the average distance from each point in a dataset
* to its nearest neighbor's location. It provides statistics about spatial distribution patterns.
*/
function nearestNeighborAnalysis(
dataset: FeatureCollection<Point>,
options?: {
studyArea?: Feature<Polygon> | Polygon | number;
units?: Units;
properties?: GeoJsonProperties;
}
): NearestNeighborStatistics;
interface NearestNeighborStatistics {
units: Units & AreaUnits;
arealUnits: string;
observedMeanDistance: number;
expectedMeanDistance: number;
nearestNeighborIndex: number;
numberOfPoints: number;
zScore: number;
}Usage Examples:
import { nearestNeighborAnalysis, randomPoint } from "@turf/turf";
// Generate random points for analysis
const points = randomPoint(50, { bbox: [-1, -1, 1, 1] });
// Perform nearest neighbor analysis
const analysis = nearestNeighborAnalysis(points, {
studyArea: 4, // Area in square units
units: 'kilometers'
});
console.log(`Observed mean distance: ${analysis.observedMeanDistance}`);
console.log(`Expected mean distance: ${analysis.expectedMeanDistance}`);
console.log(`Nearest neighbor index: ${analysis.nearestNeighborIndex}`);
console.log(`Z-score: ${analysis.zScore}`);
// Interpret results
if (analysis.nearestNeighborIndex < 1) {
console.log("Points show clustered pattern");
} else if (analysis.nearestNeighborIndex > 1) {
console.log("Points show dispersed pattern");
} else {
console.log("Points show random pattern");
}Quadrat analysis for testing spatial distribution patterns against expected random distribution.
/**
* Quadrat analysis divides the study area into equal quadrats and tests whether
* the distribution of points deviates from a random (Poisson) distribution.
*/
function quadratAnalysis(
points: FeatureCollection<Point>,
options?: {
studyBbox?: BBox;
quadratWidth?: number;
quadratHeight?: number;
units?: Units;
properties?: GeoJsonProperties;
}
): QuadratAnalysisResult;
interface QuadratAnalysisResult {
criticalValue: number;
maxAbsoluteDifference: number;
isRandom: boolean;
observedDistribution: number[];
expectedDistribution: number[];
}Usage Examples:
import { quadratAnalysis, randomPoint } from "@turf/turf";
// Generate test points
const points = randomPoint(100, { bbox: [0, 0, 10, 10] });
// Perform quadrat analysis
const result = quadratAnalysis(points, {
studyBbox: [0, 0, 10, 10],
quadratWidth: 2,
quadratHeight: 2,
units: 'kilometers'
});
console.log(`Critical value: ${result.criticalValue}`);
console.log(`Max absolute difference: ${result.maxAbsoluteDifference}`);
console.log(`Distribution is random: ${result.isRandom}`);
console.log('Observed distribution:', result.observedDistribution);
console.log('Expected distribution:', result.expectedDistribution);Calculate Moran's Index for spatial autocorrelation analysis.
/**
* Moran's Index measures spatial autocorrelation - the degree to which similar values
* cluster together in space.
*/
function moranIndex(
geojson: FeatureCollection<Polygon>,
options?: {
inputField: string;
threshold?: number;
p?: number;
standardization?: boolean;
}
): {
moranIndex: number;
expectedMoranIndex: number;
variance: number;
zNorm: number;
};Usage Examples:
import { moranIndex, randomPolygon } from "@turf/turf";
// Create polygons with test values
const polygons = randomPolygon(20, { bbox: [0, 0, 10, 10] });
polygons.features.forEach((feature, i) => {
feature.properties = { value: Math.random() * 100 };
});
// Calculate Moran's Index
const result = moranIndex(polygons, {
inputField: 'value',
threshold: 100000 // Distance threshold in meters
});
console.log(`Moran's Index: ${result.moranIndex}`);
console.log(`Expected Index: ${result.expectedMoranIndex}`);
console.log(`Z-score: ${result.zNorm}`);
// Interpret results
if (result.moranIndex > result.expectedMoranIndex) {
console.log("Positive spatial autocorrelation (clustering)");
} else if (result.moranIndex < result.expectedMoranIndex) {
console.log("Negative spatial autocorrelation (dispersion)");
} else {
console.log("No spatial autocorrelation (random)");
}Find nearest points and features for spatial analysis.
/**
* Takes a reference point and a set of points and returns the point from the set
* that is closest to the reference.
*/
function nearestPoint(
targetPoint: Coord,
points: FeatureCollection<Point>
): Feature<Point>;
/**
* Takes a Point and a LineString and calculates the closest Point on the LineString.
*/
function nearestPointOnLine(
lines: FeatureCollection<LineString> | Feature<LineString> | LineString,
pt: Coord,
options?: { units?: Units }
): Feature<Point>;
/**
* Returns the closest point on a line to a given point.
*/
function nearestPointToLine(
lines: FeatureCollection<LineString> | Feature<LineString> | LineString,
pt: Coord,
options?: { units?: Units }
): Feature<Point>;Usage Examples:
import { nearestPoint, nearestPointOnLine, randomPoint, lineString, point } from "@turf/turf";
// Find nearest point from collection
const targetPt = point([0, 0]);
const points = randomPoint(50, { bbox: [-5, -5, 5, 5] });
const nearest = nearestPoint(targetPt, points);
console.log('Nearest point:', nearest.geometry.coordinates);
// Find nearest point on line
const line = lineString([[-1, -1], [1, 1], [2, 0]]);
const pt = point([0.5, 0.8]);
const nearestOnLine = nearestPointOnLine(line, pt);
console.log('Nearest point on line:', nearestOnLine.geometry.coordinates);Calculate the standard deviational ellipse for a set of points.
/**
* Takes a collection of points and returns a standard deviational ellipse.
* The ellipse shows the distribution and directional trend of the points.
*/
function standardDeviationalEllipse(
points: FeatureCollection<Point>,
options?: {
weight?: string;
steps?: number;
properties?: GeoJsonProperties;
}
): Feature<Polygon>;Usage Examples:
import { standardDeviationalEllipse, randomPoint } from "@turf/turf";
// Generate directionally biased points
const points = randomPoint(100, { bbox: [0, 0, 4, 2] });
// Calculate standard deviational ellipse
const ellipse = standardDeviationalEllipse(points, {
steps: 64,
properties: { name: 'distribution-ellipse' }
});
console.log('Ellipse center:', ellipse.geometry.coordinates[0][0]);
console.log('Ellipse covers approximately 68% of points');Calculate distance-weighted metrics for spatial analysis.
/**
* Calculates distance-based weight between a point and a set of points,
* useful for spatial interpolation and influence analysis.
*/
function distanceWeight(
point: Coord,
points: FeatureCollection<Point>,
options?: {
threshold?: number;
p?: number;
binary?: boolean;
alpha?: number;
standardization?: boolean;
units?: Units;
}
): FeatureCollection<Point>;Usage Examples:
import { distanceWeight, point, randomPoint } from "@turf/turf";
// Calculate distance weights
const centerPt = point([0, 0]);
const points = randomPoint(20, { bbox: [-2, -2, 2, 2] });
const weighted = distanceWeight(centerPt, points, {
threshold: 1000, // meters
p: 2, // power parameter
units: 'kilometers'
});
console.log('Distance-weighted points calculated');
weighted.features.forEach((feature, i) => {
console.log(`Point ${i} weight:`, feature.properties?.weight);
});Install with Tessl CLI
npx tessl i tessl/npm-turf--turf