DOCS · COOKBOOK

Recipes & examples

Paste-ready snippets for the jobs people actually come here for. All of them assume an initialised module. See getting started for the boot lines.

Convert a vector file (+ reproject)

ogr2ogr equivalent
const ds   = await Gdal.open("/opfs/cities.geojson");
const opts = await Module.toVector("VectorString", [
  "-f", "GPKG",
  "-t_srs", "EPSG:3857",
]);
const out = await ds.vectorTranslate("/opfs/cities.gpkg", opts);
await out.close(); await ds.close();

Reproject a raster (gdalwarp)

warp
const src  = await Gdal.open("/opfs/dem.tif");
const opts = await Module.toVector("VectorString", ["-t_srs", "EPSG:4326", "-r", "bilinear"]);
const out  = await Gdal.warp("/opfs/dem-4326.tif", null, [src], opts);
await out.close(); await src.close();

Inspect metadata (gdalinfo / ogrinfo)

info as JSON
const ds   = await Gdal.open("/opfs/input.tif");
const json = JSON.parse(await ds.info(await Module.toVector("VectorString", ["-json"])));
console.log(json.bands?.length, json.coordinateSystem?.wkt);

// vector side: ds.vectorInfo(opts), and ds.multiDimInfo(opts) for multidim data

Mosaic several rasters with a VRT

buildvrt + translate
const a = await Gdal.open("/opfs/tile-a.tif");
const b = await Gdal.open("/opfs/tile-b.tif");

const vrt = await Gdal.buildVRT("/vsimem/mosaic.vrt", [a, b], [],
  await Module.toVector("VectorString", []));

const out = await vrt.translate("/opfs/mosaic.tif",
  await Module.toVector("VectorString", ["-of", "COG"]));
await out.close(); await vrt.close(); await a.close(); await b.close();

Hillshade a DEM (gdaldem)

demProcessing
const dem = await Gdal.open("/opfs/dem.tif");
const out = await dem.demProcessing(
  "/opfs/hillshade.tif",
  "hillshade",          // also: slope, aspect, color-relief, TRI, TPI, roughness
  "",                   // color file (color-relief only)
  await Module.toVector("VectorString", ["-z", "1.5"]),
);
await out.close(); await dem.close();

Open a zipped shapefile directly

/vsizip/
const ds = await Gdal.open("/vsizip//opfs/districts.zip");
// convert as usual; collect multi-file outputs with ds.getFileList()

Georeference an image with GCPs

gdal_translate -gcp equivalent
const opts = await Module.toVector("VectorString", [
  "-a_srs", "EPSG:4326",
  "-gcp", "0", "0", "28.85", "41.12",        // pixel, line, lon, lat
  "-gcp", "4000", "0", "29.15", "41.12",
  "-gcp", "4000", "3000", "29.15", "40.95",
  "-gcp", "0", "3000", "28.85", "40.95",
]);
const img = await Gdal.open("/opfs/scan.png");
const out = await img.translate("/opfs/scan-georef.tif", opts);
await out.close(); await img.close();
// programmatic alternative: the GCP class + Gdal.gcpsToGeoTransform + ds.setGCPs

Complete apps to read