forked from camptocamp/ogc-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstac-query.js
More file actions
433 lines (371 loc) · 15.3 KB
/
stac-query.js
File metadata and controls
433 lines (371 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/**
* STAC API Query Example
*
* This example demonstrates how to use the StacEndpoint class to query
* a STAC API endpoint and retrieve collections and items.
*
* Run with: node examples/stac-query.js
*/
import { StacEndpoint } from '../dist/dist-node.js';
// STAC API base URL
const STAC_API_URLS = [
'https://api.stac.teledetection.fr',
'https://catalog.maap.eo.esa.int/catalogue',
'https://stac.dataspace.copernicus.eu/v1/',
];
async function main(STAC_API_URL) {
try {
console.log('╔═══════════════════════════════════════════════════════╗');
console.log('║ STAC API Query Example ║');
console.log('╚═══════════════════════════════════════════════════════╝\n');
// Create STAC endpoint
console.log(`📡 Connecting to STAC API: ${STAC_API_URL}\n`);
const stac = new StacEndpoint(STAC_API_URL);
// Get endpoint information
console.log('1️⃣ Getting endpoint information...');
const info = await stac.info;
console.log(` Title: ${info.title || 'N/A'}`);
console.log(` Description: ${info.description}`);
console.log(` STAC Version: ${info.stacVersion}`);
console.log(` Conformance Classes: ${info.conformsTo?.length || 0}`);
console.log('');
// Check capabilities
const isStac = await stac.isStacApi;
const supportsOgc = await stac.supportsOgcFeatures;
console.log(` ✓ STAC API Core: ${isStac ? 'Yes' : 'No'}`);
console.log(` ✓ OGC API Features: ${supportsOgc ? 'Yes' : 'No'}`);
console.log('');
// List all collections
console.log('2️⃣ Listing all collections...');
const collections = await stac.allCollections;
console.log(` Found ${collections.length} collection(s):\n`);
collections.slice(0, 5).forEach((id, idx) => {
console.log(` ${idx + 1}. ${id}`);
});
if (collections.length > 5) {
console.log(` ... and ${collections.length - 5} more`);
}
console.log('');
// Get detailed information about a collection that has proper STAC items
// Use AeolusL0ProductsB16 if available, otherwise fall back to first collection
if (collections.length > 0) {
const collectionId = collections.includes('AeolusL0ProductsB16')
? 'AeolusL0ProductsB16'
: collections[0];
console.log(`3️⃣ Getting details for collection: "${collectionId}"...`);
const collection = await stac.getCollection(collectionId);
console.log(` Title: ${collection.title || 'N/A'}`);
console.log(
` Description: ${collection.description.substring(0, 100)}${
collection.description.length > 100 ? '...' : ''
}`
);
console.log(` License: ${collection.license}`);
if (collection.keywords && collection.keywords.length > 0) {
console.log(
` Keywords: ${collection.keywords.slice(0, 5).join(', ')}`
);
}
if (collection.providers && collection.providers.length > 0) {
console.log(` Provider: ${collection.providers[0].name}`);
}
// Spatial extent
if (collection.extent.spatial.bbox.length > 0) {
const bbox = collection.extent.spatial.bbox[0];
console.log(` Spatial Extent: [${bbox.join(', ')}]`);
}
// Temporal extent
if (collection.extent.temporal.interval.length > 0) {
const interval = collection.extent.temporal.interval[0];
console.log(
` Temporal Extent: ${interval[0] || 'open'} to ${
interval[1] || 'open'
}`
);
}
// Assets
if (collection.assets) {
const assetKeys = Object.keys(collection.assets);
console.log(
` Collection Assets: ${assetKeys.length} (${assetKeys
.slice(0, 3)
.join(', ')}${assetKeys.length > 3 ? '...' : ''})`
);
}
// Summaries
if (collection.summaries) {
const summaryKeys = Object.keys(collection.summaries);
console.log(` Summaries: ${summaryKeys.join(', ')}`);
}
console.log('');
// Query items from the collection
console.log(`4️⃣ Querying items from collection: "${collectionId}"...`);
console.log(' Parameters: limit=5\n');
const items = await stac.getCollectionItems(collectionId, {
limit: 5,
});
console.log(` Found ${items.length} item(s):\n`);
items.forEach((item, idx) => {
console.log(` ${idx + 1}. ${item.id}`);
console.log(` Date: ${item.properties.datetime || 'N/A'}`);
if (item.bbox) {
console.log(` BBox: [${item.bbox.join(', ')}]`);
}
if (item.properties.platform) {
console.log(` Platform: ${item.properties.platform}`);
}
if (item.properties.gsd) {
console.log(` GSD: ${item.properties.gsd}m`);
}
if (item.assets) {
const assetCount = Object.keys(item.assets).length;
const assetKeys = Object.keys(item.assets).slice(0, 3).join(', ');
console.log(
` Assets: ${assetCount} (${assetKeys}${
assetCount > 3 ? '...' : ''
})`
);
}
console.log('');
});
// Demonstrate pagination using next links (STAC standard approach)
console.log(`4️⃣b Demonstrating pagination via next links...`);
console.log(' Querying with limit=2 to get paginated results\n');
const firstPage = await stac.getCollectionItemsResponse(collectionId, {
limit: 2,
});
console.log(` First page: ${firstPage.features.length} item(s)`);
firstPage.features.forEach((item, idx) => {
console.log(` ${idx + 1}. ${item.id}`);
});
// Check for next link
const nextLink = firstPage.links?.find((link) => link.rel === 'next');
if (nextLink) {
console.log(`\n Following "next" link for pagination...`);
console.log(` Next URL: ${nextLink.href}`);
// Fetch next page using getItemsFromUrl
const nextPage = await StacEndpoint.getItemsFromUrl(nextLink.href);
console.log(`\n Second page: ${nextPage.features.length} item(s)`);
nextPage.features.forEach((item, idx) => {
console.log(` ${idx + 1}. ${item.id}`);
});
} else {
console.log(` No more pages available`);
}
console.log('');
// Demonstrate filtering by bounding box
console.log(`5️⃣ Querying items with spatial filter...`);
// Use the first item's bbox (if available) to ensure we get results
// This is more reliable than using the collection extent
let filterBbox;
if (items.length > 0 && items[0].bbox) {
const itemBbox = items[0].bbox;
// Optionally expand the bbox slightly to potentially capture nearby items
const expansion = 0.5; // degrees
filterBbox = [
itemBbox[0] - expansion, // minX (longitude)
itemBbox[1] - expansion, // minY (latitude)
itemBbox[2] + expansion, // maxX (longitude)
itemBbox[3] + expansion, // maxY (latitude)
];
console.log(
` Using bbox from first item (expanded by ${expansion}°)`
);
console.log(
` BBox: [${filterBbox.map((v) => v.toFixed(2)).join(', ')}]`
);
console.log(` Limit: 5\n`);
const filteredItems = await stac.getCollectionItems(collectionId, {
bbox: filterBbox,
limit: 5,
});
console.log(` Found ${filteredItems.length} item(s) in bbox`);
filteredItems.forEach((item, idx) => {
console.log(
` ${idx + 1}. ${item.id} - ${item.properties.datetime || 'N/A'}`
);
});
console.log('');
} else {
console.log(` Skipped: No items with bbox available\n`);
}
// Demonstrate datetime filtering
console.log(`6️⃣ Querying items with temporal filter...`);
// Use the collection's temporal extent to ensure we get results
const temporalInterval = collection.extent.temporal.interval[0];
let startDate, endDate;
if (temporalInterval && temporalInterval[0]) {
// If collection has temporal extent, query within it
startDate = new Date(temporalInterval[0]);
// Query a 30-day window starting from the collection's start date
endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + 30);
// If end date exceeds collection extent, use collection's end date
if (temporalInterval[1]) {
const collectionEnd = new Date(temporalInterval[1]);
if (endDate > collectionEnd) {
endDate = collectionEnd;
}
}
} else {
// Fallback: query recent data if no temporal extent
endDate = new Date();
startDate = new Date();
startDate.setDate(startDate.getDate() - 30);
}
console.log(
` Date range: ${startDate.toISOString().split('T')[0]} to ${
endDate.toISOString().split('T')[0]
}`
);
console.log(` Limit: 5\n`);
const recentItems = await stac.getCollectionItems(collectionId, {
datetime: { start: startDate, end: endDate },
limit: 5,
});
console.log(` Found ${recentItems.length} item(s) in date range`);
recentItems.forEach((item, idx) => {
console.log(
` ${idx + 1}. ${item.id} - ${item.properties.datetime || 'N/A'}`
);
});
console.log('');
// Get a single item
if (items.length > 0) {
const itemId = items[0].id;
console.log(`7️⃣ Getting single item: "${itemId}"...`);
const singleItem = await stac.getCollectionItem(collectionId, itemId);
console.log(` ID: ${singleItem.id}`);
console.log(` Type: ${singleItem.type}`);
console.log(` Collection: ${singleItem.collection}`);
console.log(` Geometry Type: ${singleItem.geometry?.type || 'null'}`);
// Show asset details
if (singleItem.assets) {
console.log(
`\n Assets (${Object.keys(singleItem.assets).length}):`
);
Object.entries(singleItem.assets)
.slice(0, 5)
.forEach(([key, asset]) => {
console.log(` • ${key}:`);
console.log(` Type: ${asset.type || 'N/A'}`);
console.log(` Roles: ${asset.roles?.join(', ') || 'N/A'}`);
if (asset.title) {
console.log(` Title: ${asset.title}`);
}
});
} else {
console.log(`\n No assets available`);
}
console.log('');
}
// Build a custom query URL
console.log(`8️⃣ Building custom query URL...`);
const customUrl = await stac.getCollectionItemsUrl(collectionId, {
limit: 10,
bbox: filterBbox,
datetime: { start: startDate },
});
console.log(` URL: ${customUrl}`);
console.log('');
// Demonstrate fromUrl for loading STAC resources directly
console.log(`9️⃣ Loading STAC resources with fromUrl...`);
console.log(' Auto-detects resource type from any STAC URL\n');
const collectionUrl = `${STAC_API_URL}/collections/${collectionId}`;
// Load collection
const collectionResult = await StacEndpoint.fromUrl(collectionUrl);
console.log(` • Collection URL → Type: ${collectionResult.type}`);
console.log(` Title: ${collectionResult.data.title}`);
console.log('');
// Load root/catalog
const catalogResult = await StacEndpoint.fromUrl(STAC_API_URL);
console.log(` • Root/Catalog URL → Type: ${catalogResult.type}`);
console.log(
` Title: ${catalogResult.data.title || catalogResult.data.id}`
);
console.log('');
// Load item
if (items.length > 0) {
const itemUrl = `${STAC_API_URL}/collections/${collectionId}/items/${items[0].id}`;
const itemResult = await StacEndpoint.fromUrl(itemUrl);
console.log(` • Item URL → Type: ${itemResult.type}`);
console.log(` ID: ${itemResult.data.id}`);
console.log(
` Date: ${itemResult.data.properties.datetime || 'N/A'}`
);
console.log('');
}
console.log(' ✓ All resources loaded and auto-detected successfully\n');
// Demonstrate querying items with filtering from direct items URLs
console.log(`🔟 Querying items with filtering from direct URLs...`);
console.log(
' These methods enable spatial/temporal filtering without root endpoint\n'
);
// Get the items URL from the collection
const itemsUrl = `${STAC_API_URL}/collections/${collectionId}/items`;
// Method 1: getItemsFromUrl - direct items URL query
console.log(` a) Direct query with getItemsFromUrl:`);
console.log(` Items URL: ${itemsUrl}`);
console.log(` Filters: limit=3, bbox from first item`);
if (items.length > 0 && items[0].bbox) {
const directResponse = await StacEndpoint.getItemsFromUrl(itemsUrl, {
limit: 3,
bbox: filterBbox,
});
console.log(` ✓ Found ${directResponse.features.length} item(s)`);
directResponse.features.forEach((item, idx) => {
console.log(
` ${idx + 1}. ${item.id.substring(0, 40)}${
item.id.length > 40 ? '...' : ''
}`
);
});
// Show pagination links if available
const nextLink = directResponse.links?.find((l) => l.rel === 'next');
if (nextLink) {
console.log(` → Next page available: ${nextLink.href}`);
}
} else {
console.log(` ⊘ Skipped: No items with bbox available`);
}
console.log('');
// Method 2: getItemsFromCollection - two-step for flexibility
console.log(` b) Two-step query with getItemsFromCollection:`);
console.log(` First fetch collection, then query items`);
const collectionDoc = await StacEndpoint.fromUrl(collectionUrl);
const collectionForQuery = collectionDoc.data;
console.log(` ✓ Loaded collection: ${collectionForQuery.title}`);
// Query with temporal filter
const recentDate = new Date();
recentDate.setDate(recentDate.getDate() - 30);
const collectionResponse = await StacEndpoint.getItemsFromCollection(
collectionForQuery,
{
limit: 3,
datetime: { start: recentDate },
}
);
console.log(
` ✓ Found ${collectionResponse.features.length} item(s) from last 30 days`
);
collectionResponse.features.forEach((item, idx) => {
console.log(
` ${idx + 1}. ${item.properties.datetime || 'N/A'}`
);
});
console.log('');
}
console.log('✅ Example completed successfully!\n');
} catch (error) {
console.error('\n❌ Error:', error.message);
if (error.stack) {
console.error('\nStack trace:');
console.error(error.stack);
}
process.exit(1);
}
}
// Run the example
for (const STAC_API_URL of STAC_API_URLS) {
await main(STAC_API_URL);
}