GEOS WebAssembly Bindings

3.1.1 · active · verified Tue Apr 21

geos-wasm provides a high-performance WebAssembly (WASM) build of GEOS, a robust C/C++ port of the Java Topology Suite (JTS), enabling advanced planar geometry operations directly within JavaScript environments. Currently at version 3.1.1, this library allows developers to leverage a battle-tested geospatial engine without relying on native system dependencies, making it suitable for both browser-based applications and server-side contexts like Node.js, Bun, or Deno. Built using Emscripten, geos-wasm translates GEOS's extensive C/C++ core into an efficient WebAssembly module. Its key differentiator is bringing the full power and precision of GEOS's algorithms—such as buffering, intersection, union, and area calculation—to JavaScript with a minimal setup, abstracting away the complexities of the underlying C/C++ memory management through its WASM interface. While no fixed release cadence is stated, updates typically align with upstream GEOS advancements and community-driven requirements, ensuring access to the latest topological functionalities.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the GEOS WASM module, creating a WKT reader, parsing a polygon, calculating its area, and performing crucial manual memory management by freeing allocated resources.

import initGeosJs from 'geos-wasm';

async function runGeosExample() {
  // Initialize the GEOS WebAssembly module. This returns a promise.
  const geos = await initGeosJs();

  // Use the GEOS object to call GEOS functions.
  // Example: Get the area of a polygon defined by WKT.

  // 1. Create a WKT reader.
  const reader = geos.GEOSWKTReader_create();
  const wkt = 'POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))';

  // 2. Allocate memory for the WKT string and write it.
  const size = wkt.length + 1;
  const wktPtr = geos.Module._malloc(size);
  geos.Module.stringToUTF8(wkt, wktPtr, size);

  // 3. Read the WKT string into a GEOS geometry, which returns a pointer to the geometry.
  const geomPtr = geos.GEOSWKTReader_read(reader, wktPtr);

  // 4. Allocate memory for the result (area) and calculate it.
  const areaPtr = geos.Module._malloc(8); // 8 bytes for a double
  geos.GEOSArea(geomPtr, areaPtr);

  // 5. Read the calculated area from the pointer into a JavaScript number.
  const area = geos.Module.getValue(areaPtr, 'double');

  console.log('Calculated area:', area); // Expected output: Calculated area: 1

  // 6. Crucially, free all allocated GEOS objects and memory pointers.
  geos.GEOSWKTReader_destroy(reader);
  geos.GEOSGeom_destroy(geomPtr);
  geos.GEOSFree(areaPtr); // GEOSFree for values allocated by GEOS
  geos.Module._free(wktPtr); // Module._free for values allocated by Emscripten's malloc
}

// Run the example and catch any potential errors.
runGeosExample().catch(console.error);

view raw JSON →