### GDAL Drivers Example Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md An example demonstrating how raster and vector driver information is structured and assigned. ```typescript Gdal.drivers.raster['GTiff'] = { index: 23, extension: 'tif', extensions: 'tif tiff', shortName: 'GTiff', longName: 'GeoTIFF', isReadable: true, isWritable: true, isRaster: true, isVector: false, openOptionsList: [...], creationOptionList: [...] } Gdal.drivers.vector['GeoJSON'] = { index: 75, extension: 'geojson', extensions: 'geojson', shortName: 'GeoJSON', longName: 'GeoJSON', isReadable: true, isWritable: true, isRaster: false, isVector: true } ``` -------------------------------- ### DatasetList Example Object Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md Provides an example of a DatasetList object, demonstrating how both successful datasets and error messages are represented. ```typescript { datasets: [ { pointer: 1234, path: "/input/file1.tif", type: "raster", info: {...} }, { pointer: 5678, path: "/input/file2.shp", type: "vector", info: {...} } ], errors: [ "Could not open /input/invalid.xyz" ] } ``` -------------------------------- ### Initialize GDAL3.js in Node.js with Output Directory Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Example of initializing GDAL3.js in a Node.js environment, specifying an output directory for generated files. ```javascript initGdalJs({ dest: '/tmp/gdal-output' }) ``` -------------------------------- ### Initialize GDAL3.js in Browser with CDN Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Example of initializing GDAL3.js in a browser environment using a Content Delivery Network (CDN). ```javascript initGdalJs({ path: 'https://cdn.jsdelivr.net/npm/gdal3.js@2.8.1/dist/package' }) ``` -------------------------------- ### Dataset Example Object Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md Illustrates a typical Dataset object, showing the expected format for its properties like pointer, path, type, and info. ```typescript { pointer: 12345678, path: "/input/satellite.tif", type: "raster", info: { driver: "GTiff", size: [512, 512], bands: [...] } } ``` -------------------------------- ### FilePath Example Object Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md An example object demonstrating the FilePath structure, showing virtual and real paths, and an array of all associated files. This structure is returned by functions like ogr2ogr() and gdal_translate(). ```typescript { local: "/output/data.geojson", real: "/tmp/gdaljsXYZ/data.geojson", all: [ { local: "/output/data.geojson", real: "/tmp/gdaljsXYZ/data.geojson" } ] } ``` -------------------------------- ### Initialize gdal3.js Locally Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Initialize gdal3.js after including it locally. This setup assumes the gdal3.js file is in the same directory or accessible via the path. ```javascript initGdalJs().then((Gdal) => {}); ``` -------------------------------- ### Initialize GDAL.js in Node.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-initialization.md This example shows how to initialize GDAL.js within a Node.js environment. It specifies an output directory for GDAL operations and demonstrates opening a local file. ```javascript const initGdalJs = require('gdal3.js/node'); initGdalJs({ dest: '/tmp/gdal-output' }) .then((Gdal) => { const dataset = await Gdal.open('/path/to/data.tif'); }); ``` -------------------------------- ### Raster DatasetInfo Example Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md An example object conforming to the DatasetInfo interface for a raster dataset. Includes properties like bandCount, width, height, and projection details. ```typescript { type: "raster", dsName: "/input/dem.tif", driverName: "GeoTIFF", bandCount: 1, width: 1024, height: 1024, projectionWkt: "PROJCS[\"UTM Zone 30N\"]...", coordinateTransform: [500000, 30, 0, 5000000, 0, -30], corners: [ [500000, 5000000], [530720, 5000000], [530720, 4969280], [500000, 4969280] ] } ``` -------------------------------- ### Get Raster Info with Statistics Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md This example demonstrates how to fetch detailed band statistics, including min, max, mean, and standard deviation, by passing the '-stats' option to gdalinfo. Access band-specific metadata from the returned info object. ```javascript const info = await Gdal.gdalinfo(dataset, ['-stats']); console.log('Band statistics:', info.bands[0].metadata); ``` -------------------------------- ### Vector DatasetInfo Example Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md An example object conforming to the DatasetInfo interface for a vector dataset. Includes properties like layerCount, featureCount, and an array of Layer objects. ```typescript { type: "vector", dsName: "/input/cities.geojson", driverName: "GeoJSON", layerCount: 1, featureCount: 127, layers: [ { name: "features", featureCount: 127 } ] } ``` -------------------------------- ### Initialize gdal3.js with CDN Path (No Worker) Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Initialize gdal3.js after including it from a CDN. This example explicitly sets the path and disables web workers. ```javascript initGdalJs({ path: 'https://cdn.jsdelivr.net/npm/gdal3.js@2.8.1/dist/package', useWorker: false }).then((Gdal) => {}); ``` -------------------------------- ### LocationInfo Example Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md An example of a LocationInfo object representing pixel coordinates. ```typescript { pixel: 256, line: 384 } ``` -------------------------------- ### Install gdal3.js for Builders (Webpack, React, Angular) Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Install gdal3.js using a package manager like pnpm, yarn, or npm. This is the standard approach for projects using bundlers. ```bash pnpm add gdal3.js # or yarn add gdal3.js # or npm install gdal3.js ``` -------------------------------- ### Initialize gdal3.js in Node.js Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Require and initialize gdal3.js for use in a Node.js application. This setup is for server-side or command-line usage. ```javascript const initGdalJs = require('gdal3.js/node'); initGdalJs().then((Gdal) => {}); ``` -------------------------------- ### Open Files from Filesystem (Node.js) Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-file-operations.md Opens multiple files located on the local filesystem using GDAL.js in a Node.js environment. This example shows how to pass an array of file paths to the open() function. ```javascript const result = await Gdal.open([ '/path/to/data.tif', '/path/to/vector.shp' ]); ``` -------------------------------- ### Logging Example with Custom Handlers Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/configuration.md Demonstrates how to use custom logHandler and errorHandler functions to capture all logs and errors generated by GDAL.js operations into separate arrays. ```javascript const logs = []; const errors = []; const Gdal = await initGdalJs({ path: '/static', logHandler: (msg, type) => { logs.push({ time: new Date(), type, message: msg }); }, errorHandler: (msg, type) => { errors.push({ time: new Date(), type, message: msg }); } }); // ... use Gdal ... console.log('Captured logs:', logs); console.log('Captured errors:', errors); ``` -------------------------------- ### Layer Example Object Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/types.md An example object conforming to the Layer interface, representing a vector layer with its name and feature count. Used within DatasetInfo for vector types. ```typescript { name: "buildings", featureCount: 1523 } ``` -------------------------------- ### Get Raster Dataset Info Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md Retrieves detailed information for a raster dataset, including dimensions, projection, and coordinate transform. Requires initialization of GDAL.js and opening the dataset. ```javascript const Gdal = await initGdalJs(); const dataset = (await Gdal.open('dem.tif')).datasets[0]; const info = await Gdal.getInfo(dataset); console.log('Raster Dataset:', info.dsName); console.log('Resolution:', info.width, 'x', info.height); console.log('Bands:', info.bandCount); console.log('Projection:', info.projectionWkt); // Coordinate transform for pixel-to-world conversions const [originX, scaleX, skewX, originY, skewY, scaleY] = info.coordinateTransform; console.log(`Origin: (${originX}, ${originY})`); console.log(`Pixel size: ${scaleX} x ${Math.abs(scaleY)}`); // Corners in geographic coordinates const [[minX, minY], [maxX, minY2], [maxX2, maxY], [minX2, maxY2]] = info.corners; console.log(`Bounds: [${minX}, ${minY}] to [${maxX}, ${maxY}]`); ``` -------------------------------- ### Reproject Raster to Web Mercator with Resampling Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-applications.md This example demonstrates reprojecting a raster to Web Mercator (EPSG:3857) using cubic resampling and specifying a target resolution of 30 meters. Adjust the resampling method and target resolution as needed for your application. ```javascript const dataset = (await Gdal.open('satellite.tif')).datasets[0]; const options = [ '-of', 'GTiff', '-t_srs', 'EPSG:3857', // Web Mercator '-r', 'cubic', // Cubic resampling '-tr', '30', '30' // 30m target resolution ]; const filePath = await Gdal.gdalwarp(dataset, options); ``` -------------------------------- ### GDAL.js API Structure Overview Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md This diagram illustrates the main components of the GDAL.js API, starting with initialization and leading to the Gdal object which contains methods for file operations, dataset info, vector/raster transformations, and coordinate handling. ```plaintext initGdalJs(config?) ↓ Gdal { // File Operations open() → DatasetList close() → void getFileBytes() → Uint8Array getOutputFiles() → FileInfo[] clearFS() → void // Dataset Info getInfo() → DatasetInfo gdalinfo() → object ogrinfo() → object gdal_location_info() → LocationInfo // Vector Operations ogr2ogr() → FilePath // Raster Operations gdal_translate() → FilePath gdalwarp() → FilePath gdal_rasterize() → FilePath // Coordinates gdaltransform() → number[][] // Metadata drivers → {raster: {...}, vector: {...}} } ``` -------------------------------- ### Initialize GDAL.js with Configuration Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Shows how to initialize the GDAL.js library with custom configuration options, including setting a static path, enabling workers, and defining environment variables for GDAL. ```javascript const Gdal = await initGdalJs({ path: '/static', useWorker: true, env: { 'GDAL_CACHEMAX': '512', 'GDAL_NUM_THREADS': '4' } }); ``` -------------------------------- ### Get File Bytes Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/MANIFEST.txt Retrieves the raw byte content of a file. This is useful for reading file data directly, for example, to send it over a network or process it as binary data. ```typescript import { initGdalJs, getFileBytes } from "gdal3.js"; async function readFileBytes() { await initGdalJs(); try { const fileBytes = await getFileBytes("path/to/your/file.bin"); console.log(`Read ${fileBytes.length} bytes from the file.`); // fileBytes is a Uint8Array containing the file content } catch (error) { console.error("Error reading file bytes:", error); } } readFileBytes(); ``` -------------------------------- ### Initialize GDAL3.js with Custom Handlers Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Demonstrates how to initialize GDAL3.js with custom logging and error handling functions. ```javascript initGdalJs({ logHandler: (msg) => console.log(msg), errorHandler: (msg) => console.error(msg) }) ``` -------------------------------- ### Initialize and Use gdal3.js Source: https://github.com/bugra9/gdal3.js/blob/master/apps/example-singlefile/index.html Fetches the gdal3.js worker, creates a URL for it, configures paths for WebAssembly and data files, initializes gdal3.js, and logs the number of raster and vector drivers. ```javascript async function start() { const workerData = await fetch('https://cdn.jsdelivr.net/npm/gdal3.js@2.8.1/dist/package/gdal3.js'); const workerUrl = window.URL.createObjectURL(await workerData.blob()); const paths = { wasm: 'https://cdn.jsdelivr.net/npm/gdal3.js@2.8.1/dist/package/gdal3WebAssembly.wasm', data: 'https://cdn.jsdelivr.net/npm/gdal3.js@2.8.1/dist/package/gdal3WebAssembly.data', js: workerUrl, }; const Gdal = await initGdalJs({paths}); const numberOfDrivers = Object.keys(Gdal.drivers.raster).length + Object.keys(Gdal.drivers.vector).length; document.write(`Number of driver: ${numberOfDrivers}`); } start(); ``` -------------------------------- ### Initialize and Open Datasets Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Initializes gdal3.js and opens multiple datasets, including vector (mbtiles) and raster (tif) formats. Ensure files are accessible. ```javascript const Gdal = await initGdalJs(); const files = ['a.mbtiles', 'b.tif']; // [Vector, Raster] const result = await Gdal.open(files); // https://gdal3.js.org/docs/module-f_open.html const mbTilesDataset = result.datasets[0]; const tifDataset = result.datasets[1]; ``` -------------------------------- ### Initialization Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md The main entry point for the GDAL3.js library is an asynchronous initialization function that returns a Gdal object with access to all API methods. ```APIDOC ## Initialization ### Description Initializes the GDAL3.js library and returns a Gdal object. ### Method ```typescript import initGdalJs from 'gdal3.js'; const Gdal = await initGdalJs(config?: Config): Promise ``` ### Parameters * **config** (Config) - Optional - Configuration object for initialization. ``` -------------------------------- ### GDAL3.js Initialization Flow Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md Illustrates the sequence of steps involved in initializing the GDAL3.js library, from loading WASM to returning the Gdal namespace object. ```text initGdalJs(config) ↓ Load WASM module ↓ Load data files ↓ Initialize GDAL environment ↓ Query available drivers ↓ Return Gdal namespace object ``` -------------------------------- ### Get Dataset Information Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Retrieves metadata and information about an opened dataset. This is useful for inspecting the properties of geospatial files. ```javascript getInfo() ``` -------------------------------- ### Get File Bytes Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Retrieves the processed file content as bytes. This is typically called after a conversion or transformation operation. ```javascript getFileBytes() ``` -------------------------------- ### Initialize GDAL3.js in Browser with Local Files Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Shows how to initialize GDAL3.js in a browser using local files and enabling workers for better performance. ```javascript initGdalJs({ path: '/static', useWorker: true }) ``` -------------------------------- ### Open a Dataset Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Opens a file to create a Dataset handle. Remember to call `close()` on the returned dataset when you are finished with it to prevent memory leaks. ```javascript open(file) ``` -------------------------------- ### Initialize gdal3.js in a Builder Environment Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Import and initialize gdal3.js within a project using a bundler. The 'path' option should point to the location of the gdal3.js package files. ```javascript import initGdalJs from 'gdal3.js'; initGdalJs({ path: 'static' }).then((Gdal) => {}); ``` -------------------------------- ### Initialize gdal3.js with Local Path Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/configuration.md Use this configuration when serving gdal3.js files from a local static directory. It sets the base path for library files. ```javascript initGdalJs({ path: '/static' }) ``` -------------------------------- ### Get Dataset Information Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Retrieves information about opened datasets, applicable to both vector and raster types. Use the dataset object obtained from Gdal.open(). ```javascript const mbTilesDatasetInfo = await Gdal.getInfo(mbTilesDataset); // Vector const tifDatasetInfo = await Gdal.getInfo(tifDataset); // Raster ``` -------------------------------- ### Initialize gdal3.js from CDN (No Worker) Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Use this script tag to include gdal3.js via CDN. Note that this method does not support web workers. ```html ``` -------------------------------- ### Get Location Info Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/MANIFEST.txt Retrieves information about a specific location (coordinates) within a dataset. This function is useful for finding pixel coordinates or other location-specific data. ```typescript import { initGdalJs, open, gdal_location_info } from "gdal3.js"; async function getLocationInfo() { await initGdalJs(); const datasetList = await open("path/to/your/file.tif"); if (datasetList && datasetList.length > 0) { const dataset = datasetList[0]; const coordinates = { x: 100, y: 200 }; // Example coordinates try { const locationInfo = await gdal_location_info(dataset, coordinates); console.log("Location Info:", locationInfo); } catch (error) { console.error("Error getting location info:", error); } } } getLocationInfo(); ``` -------------------------------- ### Get Dataset Information Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/MANIFEST.txt Retrieves detailed metadata about a dataset. This function returns a DatasetInfo object containing information such as dimensions, projection, and data types. ```typescript import { initGdalJs, open, getInfo } from "gdal3.js"; async function getDatasetInfo() { await initGdalJs(); const datasetList = await open("path/to/your/file.tif"); if (datasetList && datasetList.length > 0) { try { const datasetInfo = await getInfo(datasetList[0]); console.log("Dataset Info:", datasetInfo); } catch (error) { console.error("Error getting dataset info:", error); } } } getDatasetInfo(); ``` -------------------------------- ### Initialize GDAL3.js Module Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Import and initialize the GDAL3.js module. The `path` option specifies the location of GDAL3.js assets. ```typescript import initGdalJs from 'gdal3.js'; const Gdal = await initGdalJs({ path: '/static' }); ``` -------------------------------- ### Get Vector Dataset Info Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md Retrieves information for a vector dataset, including feature counts and layer details. Assumes the dataset has already been opened. ```javascript const dataset = (await Gdal.open('cities.geojson')).datasets[0]; const info = await Gdal.getInfo(dataset); console.log('Vector Dataset:', info.dsName); console.log('Total features:', info.featureCount); console.log('Layers:', info.layerCount); info.layers.forEach((layer) => { console.log(` - ${layer.name}: ${layer.featureCount} features`); }); ``` -------------------------------- ### Get Raster Dataset Information with GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Retrieves metadata about a raster dataset, such as dimensions and band count. This is useful for understanding the properties of the raster data. ```javascript const dataset = (await Gdal.open('dem.tif')).datasets[0]; const info = await Gdal.getInfo(dataset); if (info.type === 'raster') { console.log(`${info.width}x${info.height} pixels, ${info.bandCount} bands`); } ``` -------------------------------- ### Configure Vite + Vue3 for gdal3.js Initialization Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Set up a Vue3 component to import and initialize gdal3.js, specifying paths for WASM, data, and worker files using Vite's asset handling. ```html ``` -------------------------------- ### Initialize GDAL.js with Destination Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/configuration.md Initializes GDAL.js with a specified destination directory using the 'dest' option. This mounts the output directory with NODEFS, allowing files to persist on disk. ```javascript const Gdal = await initGdalJs({ dest: '/tmp/gdal-output' }); ``` ```javascript const result = await Gdal.gdal_translate(dataset, ['-of', 'PNG']); // result.local = '/output/result.png' // result.real = '/tmp/gdal-output/result.png' const fs = require('fs'); const bytes = fs.readFileSync(result.real); ``` -------------------------------- ### Transform Coordinates with GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Reprojects point coordinates from one spatial reference system to another. This example transforms coordinates from WGS84 (latitude/longitude) to Web Mercator. ```javascript const coords = [[27.143757, 38.4247972]]; // Istanbul const transformed = await Gdal.gdaltransform(coords, [ '-s_srs', 'EPSG:4326', '-t_srs', 'EPSG:3857', '-output_xy' ]); console.log(transformed); // [[3021629.21, 4639610.44]] ``` -------------------------------- ### Initialize gdal3.js in Node.js with Destination Path Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/configuration.md In Node.js environments, specify a destination directory for output files. If 'path' is omitted, it defaults to 'node_modules/gdal3.js/dist/package/'. ```javascript initGdalJs({ dest: '/tmp/output' }) ``` -------------------------------- ### Get GDAL Error Details Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/errors.md Retrieves the last GDAL error message and number, then resets the error status. Use this function when an error condition is detected. ```javascript export function getGdalError() { const message = GDALFunctions.CPLGetLastErrorMsg(); const no = GDALFunctions.CPLGetLastErrorNo(); GDALFunctions.CPLErrorReset(); return { no, message }; } ``` -------------------------------- ### Initialize gdal3.js with CDN Path Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/configuration.md Use this configuration when loading gdal3.js from a CDN. It specifies the base URL for all library files. ```javascript initGdalJs({ path: 'https://cdn.jsdelivr.net/npm/gdal3.js@2.8.1/dist/package' }) ``` -------------------------------- ### Reproject Vector Data with GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Converts vector data from one coordinate reference system to another. This example reprojects GeoJSON data to Web Mercator (EPSG:3857). ```javascript const dataset = (await Gdal.open('data.geojson')).datasets[0]; const result = await Gdal.ogr2ogr(dataset, [ '-f', 'GeoJSON', '-t_srs', 'EPSG:3857' // WGS84 → Web Mercator ]); await Gdal.close(dataset); ``` -------------------------------- ### Handling Invalid Options in GDAL Functions Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/errors.md GDAL functions reject operations with invalid command-line options. This example demonstrates how to catch rejections caused by malformed options. ```typescript const options = ['-f', 'INVALID_FORMAT']; await Gdal.ogr2ogr(dataset, options); // Will reject ``` ```typescript try { const result = await Gdal.gdal_translate(dataset, options); } catch (error) { console.error('Translation failed:', error.message); } ``` -------------------------------- ### List Output Files - JavaScript Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-file-operations.md Lists all files in the `/output/` virtual directory. Ensure GDAL.js is initialized and a dataset has been processed to generate output files. ```javascript const Gdal = await initGdalJs(); const dataset = (await Gdal.open('data.tif')).datasets[0]; const result = await Gdal.gdal_translate(dataset, ['-of', 'PNG']); const files = await Gdal.getOutputFiles(); files.forEach((file) => { console.log(`${file.path} (${file.size} bytes)`); }); ``` -------------------------------- ### Initializing gdal3.js with Custom Environment Variables Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Shows how to initialize gdal3.js with specific environment variables for cache size and thread usage. 'GDAL_NUM_THREADS': '0' enables auto-detection. ```javascript const Gdal = await initGdalJs({ env: { 'GDAL_CACHEMAX': '512', // MB 'GDAL_NUM_THREADS': '0' // Auto-detect } }); ``` -------------------------------- ### Get File Bytes from GDAL3.js Virtual Filesystem Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md Reads a file from the virtual filesystem and returns its binary contents as a Uint8Array. Returns an empty array if the file is not found. ```typescript getFileBytes(filePath: string | FilePath): Promise ``` -------------------------------- ### Initialize GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md The main export is a single function to initialize the GDAL3.js library. It takes an optional configuration object and returns a Promise that resolves to the Gdal object. ```typescript import initGdalJs from 'gdal3.js'; const Gdal = await initGdalJs(config?: Config): Promise ``` -------------------------------- ### Open Dataset with Error Checking Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Demonstrates how to open a dataset and check for both successful datasets and errors. ```javascript const result = await Gdal.open(files); result.datasets.forEach(ds => { /* use */ }); result.errors.forEach(err => { /* log */ }); ``` -------------------------------- ### Get Output Files Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/MANIFEST.txt Retrieves a list of files that have been generated as output by GDAL operations. This function returns an array of FileInfo objects, each containing details about an output file. ```typescript import { initGdalJs, getOutputFiles } from "gdal3.js"; async function listOutputFiles() { await initGdalJs(); // Assume some GDAL operations have been performed that create output files // For example, using gdal_translate or gdalwarp try { const outputFiles = await getOutputFiles(); console.log("Output files:", outputFiles); // outputFiles is an array of FileInfo objects } catch (error) { console.error("Error getting output files:", error); } } listOutputFiles(); ``` -------------------------------- ### Get Summary Vector Information Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md Retrieves only summary metadata for a vector dataset, excluding detailed geometry or feature data. Pass the '-so' option to the ogrinfo function. ```javascript const info = await Gdal.ogrinfo(dataset, ['-so']); // Returns metadata without actual geometry/feature data ``` -------------------------------- ### getOutputFiles() Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-file-operations.md Lists all files created in the `/output/` virtual directory with their paths and sizes. Returns an empty array on Node.js unless config.dest was set. ```APIDOC ## getOutputFiles() ### Description Lists all files created in the `/output/` virtual directory with their paths and sizes. Returns an empty array on Node.js (unless config.dest was set, in which case only the virtual /output filesystem is queried). ### Return Value **Type:** `Promise>` ```typescript interface FileInfo { path: string // Path to file (e.g., '/output/result.tif') size: number // File size in bytes } ``` ### Usage Examples #### List Output Files ```javascript const Gdal = await initGdalJs(); const dataset = (await Gdal.open('data.tif')).datasets[0]; const result = await Gdal.gdal_translate(dataset, ['-of', 'PNG']); const files = await Gdal.getOutputFiles(); files.forEach((file) => { console.log(`${file.path} (${file.size} bytes)`); }); ``` #### Find Specific Output File ```javascript const files = await Gdal.getOutputFiles(); const tifFile = files.find(f => f.path.endsWith('.tif')); if (tifFile) { const bytes = await Gdal.getFileBytes(tifFile.path); } ``` ``` -------------------------------- ### Include gdal3.js Locally Source: https://github.com/bugra9/gdal3.js/blob/master/README.md Include gdal3.js by referencing a local file path. This is an alternative to using a CDN. ```html ``` -------------------------------- ### Get Dataset Information with GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md Retrieves high-level structured metadata about a dataset. For raster data, it includes dimensions and projection; for vector data, it includes layers and feature counts. ```typescript getInfo(dataset: Dataset): Promise ``` -------------------------------- ### Get Basic Vector Information Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md Extracts and logs the number of layers, feature counts per layer, and field names from a vector dataset. Requires opening the dataset first. ```javascript const dataset = (await Gdal.open('roads.geojson')).datasets[0]; const info = await Gdal.ogrinfo(dataset); console.log('Layers:', info.layers.length); info.layers.forEach((layer) => { console.log(` ${layer.name}: ${layer.featureCount} features`); console.log(` Fields:`, layer.fields?.map(f => f.name).join(', ')); }); ``` -------------------------------- ### Get Basic Raster Info Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md Use this snippet to retrieve fundamental metadata about a raster dataset, such as its driver, dimensions, and band count. Ensure the dataset is opened before calling gdalinfo. ```javascript const dataset = (await Gdal.open('elevation.tif')).datasets[0]; const info = await Gdal.gdalinfo(dataset); console.log('Driver:', info.driverShortName); console.log('Size:', info.size); console.log('Bands:', info.bands.length); ``` -------------------------------- ### Initialize GDAL.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/configuration.md Initializes GDAL.js by calling the initGdalJs function. Note that some configuration settings are only effective during initialization and cannot be changed at runtime. ```javascript const Gdal = await initGdalJs(); // Note: Some settings take effect only at initialization time // For runtime changes, use GDAL options where available ``` -------------------------------- ### Rasterize Vector to Raster with GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/README.md Converts vector geometries into a raster format. This example rasterizes GeoJSON roads data into a GeoTIFF, burning a specific value and setting output dimensions. ```javascript const dataset = (await Gdal.open('roads.geojson')).datasets[0]; const result = await Gdal.gdal_rasterize(dataset, [ '-of', 'GTiff', '-burn', '255', '-ts', '512', '512' ]); ``` -------------------------------- ### initGdalJs Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-initialization.md Asynchronously initializes the gdal3.js WebAssembly library. This function must be called before using any GDAL operations. It can be called only once per session; subsequent calls return the cached promise. Configuration options allow for customization of paths, worker usage, and environment variables. ```APIDOC ## initGdalJs ### Description Asynchronously initializes the gdal3.js WebAssembly library. This function must be called before using any GDAL operations. It can be called only once per session; subsequent calls return the cached promise. On Node.js or when `config.useWorker` is false, the library initializes directly in the main thread. In browsers with `useWorker` enabled (default), the library runs in a Web Worker for non-blocking operations. ### Function Signature ```typescript function initGdalJs(config?: Config): Promise ``` ### Parameters #### Config Object - **config** (Config) - Optional - Default: `{}` - Configuration object for initialization. - **config.path** (string) - Optional - Default: `undefined` - Parent directory path for WASM and data files (browser); auto-detected on Node.js as `node_modules/gdal3.js/dist/package/`. - **config.paths** (GdalFilePaths) - Optional - Default: `undefined` - Custom file paths when names differ from defaults. - **config.paths.wasm** (string) - Optional - Default: `gdal3WebAssembly.wasm` - Path to WASM file. - **config.paths.data** (string) - Optional - Default: `gdal3WebAssembly.data` - Path to data file. - **config.paths.js** (string) - Optional - Default: `gdal3.js` - Path to JavaScript worker file. - **config.dest** (string) - Optional - Default: `undefined` - Destination path for output files (Node.js only). When set, mounts output directory with NODEFS. - **config.useWorker** (boolean) - Optional - Default: `true` - Whether to use Web Worker (browser only). Set to false for main-thread execution. - **config.env** (object) - Optional - Default: `{}` - GDAL environment variables. Applied via Module.preRun; see https://gdal.org/user/configoptions.html. - **config.logHandler** ((message: string, type: string) => void) - Optional - Default: `undefined` - Custom handler for log messages (stdout). If not provided, logs via `console.debug()`. - **config.errorHandler** ((message: string, type: string) => void) - Optional - Default: `undefined` - Custom handler for error messages (stderr). If not provided, logs via `console.error()`. ### Returns - **Promise** - A promise that resolves with the Gdal instance once the library is initialized. ``` -------------------------------- ### Rasterize Line Features Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-applications.md Rasterizes line features from a GeoJSON file into a 512x512 PNG image. This example demonstrates burning a constant value (white) and specifying a layer name if the input is multi-layered. ```javascript const dataset = (await Gdal.open('roads.geojson')).datasets[0]; const options = [ '-of', 'PNG', '-burn', '255', '-l', 'roads', // Layer name if multi-layer '-ts', '512', '512' ]; const filePath = await Gdal.gdal_rasterize(dataset, options); ``` -------------------------------- ### Get Raster Metadata using gdalinfo in GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md Wraps the GDAL `gdalinfo` utility to provide detailed raster metadata in a JSON format. This includes information about the driver, bands, projection, and geotransform. ```typescript gdalinfo( dataset: Dataset, options?: Array ): Promise ``` -------------------------------- ### List Output Files in GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md Lists all files in the `/output/` virtual directory, including their paths and sizes. Returns an array of FileInfo objects. ```typescript getOutputFiles(): Promise> ``` -------------------------------- ### Get Vector Metadata using ogrinfo in GDAL3.js Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-summary.md Wraps the GDAL `ogrinfo` utility to provide detailed vector metadata in a JSON format. This includes information about layers, fields, features, and geometry types. ```typescript ogrinfo( dataset: Dataset, options?: Array ): Promise ``` -------------------------------- ### Open File from Network URL (Browser) Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-file-operations.md Demonstrates opening a file from a network URL in a browser environment. It fetches the file as a Blob, converts it to a File object, and then opens it using Gdal.open(). ```javascript const response = await fetch('https://example.com/data.geojson'); const blob = await response.blob(); const file = new File([blob], 'data.geojson', { type: 'application/geo+json' }); const result = await Gdal.open(file); ``` -------------------------------- ### Determine Processing Strategy Based on Dataset Type Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-dataset-info.md Uses dataset information to dynamically decide on a processing strategy for raster or vector data. This example demonstrates conditional logic based on the 'type' property of the dataset info. ```javascript const dataset = (await Gdal.open(file)).datasets[0]; const info = await Gdal.getInfo(dataset); if (info.type === 'raster') { console.log(`Processing ${info.width}x${info.height} raster with ${info.bandCount} bands`); if (info.bandCount === 3) { // Likely RGB image } else if (info.bandCount === 1) { // Single band (grayscale or data) } } else { console.log(`Processing vector with ${info.featureCount} features in ${info.layerCount} layers`); } ``` -------------------------------- ### open() Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-file-operations.md Opens one or more files and returns a list of successfully opened datasets and errors for files that failed to open. Supports files from HTML input elements, network URLs, the local filesystem (Node.js), and virtual paths. ```APIDOC ## open() ### Description Opens one or more files and returns a list of successfully opened datasets and errors for files that failed to open. Supports files from HTML input elements, network URLs, the local filesystem (Node.js), and virtual paths (`/input/` and `/output/`). Files are automatically analyzed to determine their type (raster or vector) using `gdalinfo` or `ogrinfo`. Datasets must be closed with `close()` to prevent memory leaks. ### Function Signature ```typescript function open( fileOrFiles: FileList | File | Array | string, openOptions?: Array, VFSHandlers?: Array ): Promise ``` ### Parameters #### Path Parameters - **fileOrFiles** (FileList | File | Array | string) - Required - Single file or multiple files to open - **openOptions** (Array) - Optional - Open options passed to GDAL drivers. Format: `['OPT1=VAL1', 'OPT2=VAL2']` - **VFSHandlers** (Array) - Optional - Virtual file system handlers like `vsizip`, `vsicurl`, `vsiaz`. Example: `['vsizip']` for ZIP files ### Return Value **Type:** `Promise` ```typescript interface DatasetList { datasets: Array errors: Array } interface Dataset { pointer: number // Memory address of dataset path: string // Local path within Gdal filesystem type: string // 'raster' or 'vector' info: object // Result from gdalinfo or ogrinfo } ``` Resolves even if some files fail to open (check `errors` array). Rejects only if all files fail and `datasets.length === 0`. ### Throws - **Error[]** - If all files fail to open, promise rejects with array of error objects ### Usage Examples #### Single File from HTML Input ```javascript const Gdal = await initGdalJs(); document.getElementById('file-input').addEventListener('change', async (event) => { const file = event.target.files[0]; const result = await Gdal.open(file); if (result.datasets.length > 0) { const dataset = result.datasets[0]; console.log(`Opened ${dataset.type} file:`, dataset.path); } if (result.errors.length > 0) { console.error('Errors:', result.errors); } }); ``` #### Multiple Files from File Input ```javascript document.getElementById('multi-file-input').addEventListener('change', async (event) => { const result = await Gdal.open(event.target.files); result.datasets.forEach((dataset) => { console.log(`${dataset.path} (${dataset.type})`); }); }); ``` #### File from Network (Browser) ```javascript const response = await fetch('https://example.com/data.geojson'); const blob = await response.blob(); const file = new File([blob], 'data.geojson', { type: 'application/geo+json' }); const result = await Gdal.open(file); ``` #### Files from Filesystem (Node.js) ```javascript const result = await Gdal.open([ '/path/to/data.tif', '/path/to/vector.shp' ]); ``` #### CSV File with Open Options (Node.js) ```javascript const result = await Gdal.open('data.csv', ['X_POSSIBLE_NAMES=lng', 'Y_POSSIBLE_NAMES=lat']); ``` #### ZIP Shapefile (Browser/Node.js) ```javascript const result = await Gdal.open('shapefile.zip', [], ['vsizip']); ``` #### Virtual Path Files ```javascript // After a previous operation created /output/result.tif const result = await Gdal.open('/output/result.tif'); // Files in /input are those opened earlier const result2 = await Gdal.open('/input/original.shp'); ``` ``` -------------------------------- ### Checking Available Output Formats Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/errors.md Before attempting to write to a specific format, verify its availability. This snippet shows how to list available raster drivers and check for a specific format like PNG. ```typescript const availableFormats = Object.keys(Gdal.drivers.raster); if (!availableFormats.includes('PNG')) { console.error('PNG driver not available'); } ``` -------------------------------- ### Handling Projection and Transformation Errors Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/errors.md Errors related to invalid spatial reference systems (SRS) or incompatible coordinate transformations can occur during operations like `gdalwarp`. This example shows how to catch such errors and check for specific messages. ```typescript const options = ['-t_srs', 'INVALID_EPSG']; await Gdal.gdalwarp(dataset, options); // Will reject ``` ```typescript try { const result = await Gdal.gdalwarp(dataset, ['-t_srs', 'EPSG:4326']); } catch (error) { if (error.message.includes('SRS')) { console.error('Check the target SRS code'); } } ``` -------------------------------- ### Handle GDAL.js Initialization Errors Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-initialization.md Demonstrates how to catch errors that may occur during GDAL.js initialization, such as missing WASM files or corrupted data. This is useful for providing user feedback or fallback mechanisms. ```javascript initGdalJs({ path: '/static' }) .then((Gdal) => { // Use Gdal }) .catch((error) => { console.error('Failed to initialize GDAL:', error.message); }); ``` -------------------------------- ### Open CSV File with Open Options (Node.js) Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/api-reference-file-operations.md Opens a CSV file and specifies custom open options to guide GDAL's parsing. This is useful for explicitly defining coordinate columns like 'lng' and 'lat'. ```javascript const result = await Gdal.open('data.csv', ['X_POSSIBLE_NAMES=lng', 'Y_POSSIBLE_NAMES=lat']); ``` -------------------------------- ### Initialize GDAL3.JS Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/MANIFEST.txt Initializes the GDAL3.JS module. This function should be called before any other GDAL operations. It returns a Promise that resolves with the Gdal instance. ```typescript import { initGdalJs } from "gdal3.js"; async function initialize() { const gdal = await initGdalJs({ // Configuration options can be provided here // For example, to set a custom VFS handler: // VFS: new MyVFSHandler() }); console.log("GDAL3.JS initialized successfully."); // Now you can use other GDAL functions } initialize(); ``` -------------------------------- ### GDAL3.js Initialization Source: https://github.com/bugra9/gdal3.js/blob/master/_autodocs/INDEX.md Initializes the GDAL3.js module. This is the first step before using any other GDAL3.js functionalities. It can accept a configuration object for customization. ```APIDOC ## initGdalJs(config?) ### Description Initializes the GDAL3.js module. This function should be called before any other GDAL3.js operations. An optional configuration object can be provided to customize the initialization process, such as setting up workers. ### Method `initGdalJs` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (object) - Optional - Configuration options for initialization, including worker setup. ```