0
# Advanced Spatial Analysis
1
2
Advanced statistical analysis functions for spatial pattern detection, nearest neighbor analysis, spatial autocorrelation, and other sophisticated geospatial analytics.
3
4
## Capabilities
5
6
### Nearest Neighbor Analysis
7
8
Comprehensive nearest neighbor statistical analysis for spatial distribution patterns.
9
10
```typescript { .api }
11
/**
12
* Nearest neighbor analysis measures the average distance from each point in a dataset
13
* to its nearest neighbor's location. It provides statistics about spatial distribution patterns.
14
*/
15
function nearestNeighborAnalysis(
16
dataset: FeatureCollection<Point>,
17
options?: {
18
studyArea?: Feature<Polygon> | Polygon | number;
19
units?: Units;
20
properties?: GeoJsonProperties;
21
}
22
): NearestNeighborStatistics;
23
24
interface NearestNeighborStatistics {
25
units: Units & AreaUnits;
26
arealUnits: string;
27
observedMeanDistance: number;
28
expectedMeanDistance: number;
29
nearestNeighborIndex: number;
30
numberOfPoints: number;
31
zScore: number;
32
}
33
```
34
35
**Usage Examples:**
36
37
```typescript
38
import { nearestNeighborAnalysis, randomPoint } from "@turf/turf";
39
40
// Generate random points for analysis
41
const points = randomPoint(50, { bbox: [-1, -1, 1, 1] });
42
43
// Perform nearest neighbor analysis
44
const analysis = nearestNeighborAnalysis(points, {
45
studyArea: 4, // Area in square units
46
units: 'kilometers'
47
});
48
49
console.log(`Observed mean distance: ${analysis.observedMeanDistance}`);
50
console.log(`Expected mean distance: ${analysis.expectedMeanDistance}`);
51
console.log(`Nearest neighbor index: ${analysis.nearestNeighborIndex}`);
52
console.log(`Z-score: ${analysis.zScore}`);
53
54
// Interpret results
55
if (analysis.nearestNeighborIndex < 1) {
56
console.log("Points show clustered pattern");
57
} else if (analysis.nearestNeighborIndex > 1) {
58
console.log("Points show dispersed pattern");
59
} else {
60
console.log("Points show random pattern");
61
}
62
```
63
64
### Quadrat Analysis
65
66
Quadrat analysis for testing spatial distribution patterns against expected random distribution.
67
68
```typescript { .api }
69
/**
70
* Quadrat analysis divides the study area into equal quadrats and tests whether
71
* the distribution of points deviates from a random (Poisson) distribution.
72
*/
73
function quadratAnalysis(
74
points: FeatureCollection<Point>,
75
options?: {
76
studyBbox?: BBox;
77
quadratWidth?: number;
78
quadratHeight?: number;
79
units?: Units;
80
properties?: GeoJsonProperties;
81
}
82
): QuadratAnalysisResult;
83
84
interface QuadratAnalysisResult {
85
criticalValue: number;
86
maxAbsoluteDifference: number;
87
isRandom: boolean;
88
observedDistribution: number[];
89
expectedDistribution: number[];
90
}
91
```
92
93
**Usage Examples:**
94
95
```typescript
96
import { quadratAnalysis, randomPoint } from "@turf/turf";
97
98
// Generate test points
99
const points = randomPoint(100, { bbox: [0, 0, 10, 10] });
100
101
// Perform quadrat analysis
102
const result = quadratAnalysis(points, {
103
studyBbox: [0, 0, 10, 10],
104
quadratWidth: 2,
105
quadratHeight: 2,
106
units: 'kilometers'
107
});
108
109
console.log(`Critical value: ${result.criticalValue}`);
110
console.log(`Max absolute difference: ${result.maxAbsoluteDifference}`);
111
console.log(`Distribution is random: ${result.isRandom}`);
112
console.log('Observed distribution:', result.observedDistribution);
113
console.log('Expected distribution:', result.expectedDistribution);
114
```
115
116
### Moran's Index (Spatial Autocorrelation)
117
118
Calculate Moran's Index for spatial autocorrelation analysis.
119
120
```typescript { .api }
121
/**
122
* Moran's Index measures spatial autocorrelation - the degree to which similar values
123
* cluster together in space.
124
*/
125
function moranIndex(
126
geojson: FeatureCollection<Polygon>,
127
options?: {
128
inputField: string;
129
threshold?: number;
130
p?: number;
131
standardization?: boolean;
132
}
133
): {
134
moranIndex: number;
135
expectedMoranIndex: number;
136
variance: number;
137
zNorm: number;
138
};
139
```
140
141
**Usage Examples:**
142
143
```typescript
144
import { moranIndex, randomPolygon } from "@turf/turf";
145
146
// Create polygons with test values
147
const polygons = randomPolygon(20, { bbox: [0, 0, 10, 10] });
148
polygons.features.forEach((feature, i) => {
149
feature.properties = { value: Math.random() * 100 };
150
});
151
152
// Calculate Moran's Index
153
const result = moranIndex(polygons, {
154
inputField: 'value',
155
threshold: 100000 // Distance threshold in meters
156
});
157
158
console.log(`Moran's Index: ${result.moranIndex}`);
159
console.log(`Expected Index: ${result.expectedMoranIndex}`);
160
console.log(`Z-score: ${result.zNorm}`);
161
162
// Interpret results
163
if (result.moranIndex > result.expectedMoranIndex) {
164
console.log("Positive spatial autocorrelation (clustering)");
165
} else if (result.moranIndex < result.expectedMoranIndex) {
166
console.log("Negative spatial autocorrelation (dispersion)");
167
} else {
168
console.log("No spatial autocorrelation (random)");
169
}
170
```
171
172
### Spatial Search and Nearest Points
173
174
Find nearest points and features for spatial analysis.
175
176
```typescript { .api }
177
/**
178
* Takes a reference point and a set of points and returns the point from the set
179
* that is closest to the reference.
180
*/
181
function nearestPoint(
182
targetPoint: Coord,
183
points: FeatureCollection<Point>
184
): Feature<Point>;
185
186
/**
187
* Takes a Point and a LineString and calculates the closest Point on the LineString.
188
*/
189
function nearestPointOnLine(
190
lines: FeatureCollection<LineString> | Feature<LineString> | LineString,
191
pt: Coord,
192
options?: { units?: Units }
193
): Feature<Point>;
194
195
/**
196
* Returns the closest point on a line to a given point.
197
*/
198
function nearestPointToLine(
199
lines: FeatureCollection<LineString> | Feature<LineString> | LineString,
200
pt: Coord,
201
options?: { units?: Units }
202
): Feature<Point>;
203
```
204
205
**Usage Examples:**
206
207
```typescript
208
import { nearestPoint, nearestPointOnLine, randomPoint, lineString, point } from "@turf/turf";
209
210
// Find nearest point from collection
211
const targetPt = point([0, 0]);
212
const points = randomPoint(50, { bbox: [-5, -5, 5, 5] });
213
const nearest = nearestPoint(targetPt, points);
214
215
console.log('Nearest point:', nearest.geometry.coordinates);
216
217
// Find nearest point on line
218
const line = lineString([[-1, -1], [1, 1], [2, 0]]);
219
const pt = point([0.5, 0.8]);
220
const nearestOnLine = nearestPointOnLine(line, pt);
221
222
console.log('Nearest point on line:', nearestOnLine.geometry.coordinates);
223
```
224
225
### Standard Deviational Ellipse
226
227
Calculate the standard deviational ellipse for a set of points.
228
229
```typescript { .api }
230
/**
231
* Takes a collection of points and returns a standard deviational ellipse.
232
* The ellipse shows the distribution and directional trend of the points.
233
*/
234
function standardDeviationalEllipse(
235
points: FeatureCollection<Point>,
236
options?: {
237
weight?: string;
238
steps?: number;
239
properties?: GeoJsonProperties;
240
}
241
): Feature<Polygon>;
242
```
243
244
**Usage Examples:**
245
246
```typescript
247
import { standardDeviationalEllipse, randomPoint } from "@turf/turf";
248
249
// Generate directionally biased points
250
const points = randomPoint(100, { bbox: [0, 0, 4, 2] });
251
252
// Calculate standard deviational ellipse
253
const ellipse = standardDeviationalEllipse(points, {
254
steps: 64,
255
properties: { name: 'distribution-ellipse' }
256
});
257
258
console.log('Ellipse center:', ellipse.geometry.coordinates[0][0]);
259
console.log('Ellipse covers approximately 68% of points');
260
```
261
262
### Distance Weight Analysis
263
264
Calculate distance-weighted metrics for spatial analysis.
265
266
```typescript { .api }
267
/**
268
* Calculates distance-based weight between a point and a set of points,
269
* useful for spatial interpolation and influence analysis.
270
*/
271
function distanceWeight(
272
point: Coord,
273
points: FeatureCollection<Point>,
274
options?: {
275
threshold?: number;
276
p?: number;
277
binary?: boolean;
278
alpha?: number;
279
standardization?: boolean;
280
units?: Units;
281
}
282
): FeatureCollection<Point>;
283
```
284
285
**Usage Examples:**
286
287
```typescript
288
import { distanceWeight, point, randomPoint } from "@turf/turf";
289
290
// Calculate distance weights
291
const centerPt = point([0, 0]);
292
const points = randomPoint(20, { bbox: [-2, -2, 2, 2] });
293
294
const weighted = distanceWeight(centerPt, points, {
295
threshold: 1000, // meters
296
p: 2, // power parameter
297
units: 'kilometers'
298
});
299
300
console.log('Distance-weighted points calculated');
301
weighted.features.forEach((feature, i) => {
302
console.log(`Point ${i} weight:`, feature.properties?.weight);
303
});
304
```