geos clib

GEOS geometry engine for PascalAI. The spatial library behind PostGIS, QGIS, and GeoPandas — spatial predicates (contains, intersects, within), operations (buffer, union, intersection, difference), measurements (area, distance), WKT/WKB/GeoJSON I/O, and geometry simplification.

Version1.0.0
Typeclib
System reqlibgeos-dev
CategoryGeospatial
ppm install geos
CLib package — system library required

Ubuntu/Debian: sudo apt install libgeos-dev  •  Fedora: sudo dnf install geos-devel  •  macOS: brew install geos

Quick Start

uses geos;

GEOSInit;

{ Parse WKT geometries }
var paris  := FromWKT('POINT(2.3488 48.8534)');
var france := FromWKT('POLYGON((...many coordinates...))');

{ Spatial predicate }
if Within(paris, france) then
  WriteLn('Paris is in France');

{ Buffer a point to create a circle (0.1 degree radius, 32 segments) }
var circle := Buffer(paris, 0.1, 32);
WriteLn('Circle area: ' + FloatToStr(Area(circle)));

FreeGeom(paris);
FreeGeom(france);
FreeGeom(circle);
GEOSCleanup;
uses geos;

GEOSInit;

{ Compute intersection of two overlapping squares }
var polyA := FromWKT('POLYGON((0 0,4 0,4 4,0 4,0 0))');
var polyB := FromWKT('POLYGON((2 2,6 2,6 6,2 6,2 2))');

var inter := Intersection(polyA, polyB);
WriteLn('Intersection: ' + ToWKT(inter));
WriteLn('Area:         ' + FloatToStr(Area(inter)));

var dist := Distance(polyA, polyB);
WriteLn('Distance:     ' + FloatToStr(dist));

FreeGeom(polyA);
FreeGeom(polyB);
FreeGeom(inter);
GEOSCleanup;

Context API

Call GEOSInit once at startup and GEOSCleanup at shutdown. For multi-threaded programs use explicit contexts.

FunctionDescription
GEOSInit()Initialize the default GEOS context. Must be called before any other GEOS function.
GEOSCleanup()Release the default context and all associated memory.
NewContext()Create an independent GEOS context for use in a separate thread.
FreeContext(ctx)Release an explicit context.
GEOSVersion()Returns GEOS library version string (e.g. '3.12.1').
SetNoticeHandler(handler)Set a callback function for GEOS notice/warning messages.
SetErrorHandler(handler)Set a callback function for GEOS error messages.

WKT I/O API

Well-Known Text is the standard human-readable geometry format. POINT(lon lat), LINESTRING(...), POLYGON((...outer ring...)).

FunctionDescription
FromWKT(wkt)Parse WKT string into a geometry handle. Raises exception on invalid input.
ToWKT(geom)Serialize geometry to WKT string.
ToWKTTrimmed(geom)WKT with trailing zeros trimmed (e.g. POINT (2 48) instead of POINT (2.000000 48.000000)).
ToWKTPrecision(geom, decimals)WKT with fixed number of decimal places.

WKB I/O API

Well-Known Binary is the compact binary geometry encoding used by databases (PostGIS, SpatiaLite, GeoPackage).

FunctionDescription
FromWKB(bytes)Parse WKB byte array into a geometry handle.
FromHexWKB(hex)Parse hex-encoded WKB string (as returned by PostGIS queries).
ToWKB(geom)Serialize geometry to WKB byte array (little-endian).
ToHexWKB(geom)Serialize to hex-encoded WKB string.
ToEWKB(geom, srid)Serialize to PostGIS Extended WKB with embedded SRID.

GeoJSON I/O API

FunctionDescription
FromGeoJSON(json)Parse a GeoJSON geometry string into a geometry handle.
ToGeoJSON(geom)Serialize geometry to a GeoJSON geometry string.
ToGeoJSONPretty(geom)Indented, human-readable GeoJSON output.
uses geos;

GEOSInit;

var json := '{"type":"Polygon","coordinates":[[[0,0],[4,0],[4,4],[0,4],[0,0]]]}';
var poly := FromGeoJSON(json);

WriteLn('Type:  ' + GeomType(poly));   { 'Polygon' }
WriteLn('Area:  ' + FloatToStr(Area(poly)));
WriteLn('WKT:   ' + ToWKTTrimmed(poly));

FreeGeom(poly);
GEOSCleanup;

Geometry Constructors API

FunctionDescription
MakePoint(x, y)Create a 2D Point geometry.
MakePointZ(x, y, z)Create a 3D Point geometry.
MakeLineString(coords)Create LineString from array of TCoord.
MakePolygon(shell, holes)Create Polygon from exterior ring + optional holes (arrays of TCoord).
MakePolygonFromBox(minX, minY, maxX, maxY)Create a rectangular Polygon from bounding box.
MakeMultiPoint(geoms)Create MultiPoint from geometry array.
MakeMultiLineString(geoms)Create MultiLineString from geometry array.
MakeMultiPolygon(geoms)Create MultiPolygon from geometry array.
MakeGeometryCollection(geoms)Create heterogeneous GeometryCollection.
CloneGeom(geom)Deep clone a geometry handle.
FreeGeom(geom)Release a geometry handle.

Spatial Predicates

All predicates return Boolean. The first argument is the subject; the second is the object. E.g. Contains(a, b) returns True if a completely contains b.

FunctionDescriptionDE-9IM pattern
Contains(a, b)True if a contains every point of b, including the boundary.T*****FF*
Intersects(a, b)True if a and b share at least one point. Opposite of Disjoint.!FF*FF****
Within(a, b)True if a is completely inside b (inverse of Contains).T*F**F***
Overlaps(a, b)True if a and b share some but not all interior points and have the same dimension.T*T***T**
Touches(a, b)True if geometries share boundary points but no interior points.FT*******
Disjoint(a, b)True if a and b share no points whatsoever.FF*FF****
Crosses(a, b)True if geometries share some interior points and their intersection has a lower dimension than both.T*T******
Equals(a, b)True if a and b represent the same point set (topologically equal).T*F**FFF*
Covers(a, b)True if no point of b is outside a. Like Contains but includes boundary.
CoveredBy(a, b)True if no point of a is outside b (inverse of Covers).

Spatial Operations API

All operations return new geometry handles. Remember to call FreeGeom on results when done.

FunctionDescription
Buffer(geom, dist, segments)Expand (positive dist) or shrink (negative dist) geometry by distance. segments controls circle approximation quality.
GUnion(a, b)Union of two geometries (merged area with no overlaps).
UnionAll(geoms)Cascaded union of a geometry array. More efficient than repeated GUnion calls.
Intersection(a, b)Intersection: the shared area between two geometries.
Difference(a, b)Part of a that does not intersect b.
SymDifference(a, b)Parts of each geometry that are not in the intersection (XOR of areas).
ConvexHull(geom)Smallest convex polygon that encloses the geometry.
Centroid(geom)Point geometry at the arithmetic center of mass.
PointOnSurface(geom)A guaranteed interior point, even for concave or non-convex geometries.
Envelope(geom)Minimum bounding rectangle (as a Polygon).
Boundary(geom)Boundary of the geometry (e.g. outer ring of a polygon).
LineMerge(geom)Merge a collection of line segments into longer linestrings.
Node(geom)Node a geometry (add intersection points on crossing edges).
uses geos;

GEOSInit;

{ Build a 500m buffer around a point, test containment }
var center  := MakePoint(2.3488, 48.8534);
var zone    := Buffer(center, 0.005, 64);  { ~0.005 deg ≈ 500m }

var nearby  := MakePoint(2.3510, 48.8550);
var faraway := MakePoint(2.4000, 48.9000);

WriteLn('nearby in zone:  ' + BoolToStr(Within(nearby, zone)));
WriteLn('faraway in zone: ' + BoolToStr(Within(faraway, zone)));

WriteLn('Zone area: ' + FloatToStr(Area(zone)));
WriteLn('Centroid:  ' + ToWKTTrimmed(Centroid(zone)));

FreeGeom(center);  FreeGeom(zone);
FreeGeom(nearby);  FreeGeom(faraway);
GEOSCleanup;

Measurements API

FunctionDescription
Area(geom)Area of a polygon geometry in coordinate units squared.
Length(geom)Perimeter (polygon) or total length (linestring) in coordinate units.
Distance(a, b)Minimum distance between any point in a and any point in b.
HausdorffDistance(a, b)Hausdorff distance — maximum of minimum distances in both directions. Measures shape similarity.
FrechetDistance(a, b)Frechet distance between curves — useful for comparing trajectory shape.
NearestPoints(a, b)Returns array of two TCoord: the closest points on a and b respectively.
Coordinate units

GEOS operates in the units of the coordinate system you provide. For WGS84 (lon/lat), area is in degrees-squared and distance is in degrees — not very useful. Reproject coordinates to a metric CRS (UTM, Web Mercator) using the proj package before computing areas and distances.

Simplification API

FunctionDescription
Simplify(geom, tolerance)Douglas-Peucker simplification. May produce invalid geometries (self-intersections).
SimplifyPreserveTopology(geom, tolerance)Simplification that guarantees valid output. Slightly slower than Simplify.
DensifyByLength(geom, maxSegLen)Add extra vertices so no segment is longer than maxSegLen.

Validity API

FunctionDescription
IsValid(geom)Returns True if geometry is topologically valid (no self-intersections, etc.).
IsValidReason(geom)Returns a string explaining why the geometry is invalid, or 'Valid Geometry'.
MakeValid(geom)Attempt to repair invalid geometry. Returns a new valid geometry handle.
IsEmpty(geom)True if the geometry is empty (contains no coordinates).
IsSimple(geom)True if the geometry does not self-intersect.
IsRing(geom)True if a LineString is closed and simple (forms a ring).
GeomType(geom)Returns geometry type string: 'Point', 'Polygon', 'LineString', etc.
GeomTypeId(geom)Returns integer type code (0=Point, 1=LineString, 3=Polygon, etc.).
SRID(geom)Returns the SRID (spatial reference ID) embedded in the geometry, or 0.
SetSRID(geom, srid)Embed an SRID in the geometry (does not reproject).
NumGeometries(geom)Number of sub-geometries in a collection, or 1 for simple types.
GetGeometry(geom, i)Get the i-th sub-geometry from a collection (zero-indexed).
NumCoordinates(geom)Total number of coordinate vertices in the geometry.

Prepared Geometry API

When testing one geometry (e.g. a region polygon) against many others repeatedly, use a prepared geometry. It pre-computes internal indexes so each subsequent predicate test is much faster.

FunctionDescription
Prepare(geom)Create a prepared geometry handle from an existing geometry. Indexes are built at this call.
FreePrepared(prep)Release a prepared geometry (the underlying geometry is not freed).
PrepContains(prep, geom)Fast Contains test using the prepared geometry.
PrepIntersects(prep, geom)Fast Intersects test.
PrepWithin(prep, geom)Fast Within test.
PrepCovers(prep, geom)Fast Covers test.
PrepCoveredBy(prep, geom)Fast CoveredBy test.
uses geos;

GEOSInit;

{ Prepare a region polygon once, then test thousands of points }
var region := FromWKT('POLYGON((-5 36,5 36,5 44,-5 44,-5 36))');
var prep   := Prepare(region);  { builds spatial index }

var points := ['POINT(-3.70 40.41)', 'POINT(2.35 48.85)',
               'POINT(0.12 51.50)', 'POINT(-0.81 37.97)'];
for var wkt in points do
begin
  var pt := FromWKT(wkt);
  WriteLn(wkt + ': ' + BoolToStr(PrepContains(prep, pt)));
  FreeGeom(pt);
end;

FreePrepared(prep);
FreeGeom(region);
GEOSCleanup;

Geometry Types

Point

A single (x, y) or (x, y, z) coordinate. E.g. POINT(2.35 48.85).

LineString

An ordered sequence of two or more points connected by straight segments.

LinearRing

A closed LineString (first and last points are identical). Used as polygon rings.

Polygon

An exterior ring plus zero or more interior rings (holes). Must be valid (non-self-intersecting).

MultiPoint

A collection of Point geometries treated as a single spatial object.

MultiLineString

A collection of LineString geometries. May be connected or disconnected.

MultiPolygon

A collection of Polygon geometries. E.g. an archipelago or a country with islands.

GeometryCollection

A heterogeneous collection of any geometry types (mix of points, lines, polygons).

Memory management

Every geometry-returning function allocates a new handle. Always call FreeGeom on results you no longer need. Intermediate geometries created by operations (Buffer, Intersection, etc.) are independent handles that also require explicit freeing. Forgetting to free results is the most common source of memory leaks when using GEOS.