geo

package
v0.0.0-debug-20260702 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package geo is MatrixOne's self-contained GIS engine: the geometry model, WKT/WKB readers and writers, and the Cartesian (planar) and geodetic (spherical, via github.com/golang/geo) algorithm kernels.

It has no dependency on pkg/sql so it can be unit-tested in isolation. The SQL layer stores geometry values as bare WKB inside a varlena and supplies the SRID from the column type; this package never embeds an SRID in the bytes it produces.

Index

Constants

View Source
const (
	// SRIDPlanar is unitless planar (Cartesian) geometry.
	SRIDPlanar uint32 = 0
	// SRIDWGS84 is WGS 84 longitude/latitude; computations are geodetic and
	// return meters / square meters.
	SRIDWGS84 uint32 = 4326
)

SRID values supported by the engine. Any other SRID is rejected by the computation kernels.

View Source
const EarthRadiusMeters = 6371008.8

EarthRadiusMeters is the IUGG mean Earth radius (R1). S2 computes on a unit sphere; multiplying angular results by this radius yields meters. Because S2 is spherical (not ellipsoidal), geodetic results differ slightly from MySQL/PostGIS ellipsoidal values — callers compare with tolerance.

View Source
const MaxSRID uint32 = 1<<31 - 2 // math.MaxInt32 - 1

MaxSRID is the largest SRID the SQL layer can persist. The SRID is carried in the column/expression type's int32 Width as srid+1 (0 means "undefined"), so the usable range is [0, math.MaxInt32-1]. Larger values would overflow Width and silently collapse (e.g. 4294967295+1 wraps to the undefined sentinel), so the SQL layer rejects them.

Variables

This section is empty.

Functions

func AreaSquareMeters

func AreaSquareMeters(g Geometry) float64

AreaSquareMeters returns the geodesic area of all areal components of g.

func CartesianArea

func CartesianArea(g Geometry) float64

CartesianArea returns the planar area of g (0 for non-areal geometries).

func CartesianDistance

func CartesianDistance(g1, g2 Geometry) (dist float64, ok bool)

CartesianDistance returns the minimum planar distance between g1 and g2. ok is false when either geometry is empty. The distance is 0 when the geometries intersect (touch, cross, or one contains the other).

func CartesianLength

func CartesianLength(g Geometry) float64

CartesianLength returns the total length of all line components of g (0 for points and polygons).

func CartesianPerimeter

func CartesianPerimeter(g Geometry) float64

CartesianPerimeter returns the total ring length of all areal components of g (0 for points and lines).

func DecodeGeoHash

func DecodeGeoHash(hash string) (lon, lat float64, err error)

DecodeGeoHash decodes a geohash into the center longitude/latitude of the cell it denotes.

func DistanceMeters

func DistanceMeters(g1, g2 Geometry) (dist float64, ok bool)

DistanceMeters returns the minimum geodesic distance in meters between g1 and g2. ok is false when either geometry is empty. The distance is 0 when the geometries intersect or one contains a point of the other.

func EncodeGeoHash

func EncodeGeoHash(lon, lat float64, length int) string

EncodeGeoHash encodes a (longitude, latitude) position into a geohash string of the given character length. Bits interleave longitude-first; each base32 character carries 5 bits.

func FrechetDistance

func FrechetDistance(a, b Geometry) (float64, bool)

FrechetDistance returns the discrete Fréchet distance (planar) between the vertex sequences of two geometries, via the Eiter-Mannila dynamic program.

func GeodeticContainsPoint

func GeodeticContainsPoint(c Coord, p Polygon) bool

GeodeticContainsPoint reports whether c lies within polygon p on the sphere (interior; a point exactly on the boundary is treated as contained by S2's loop containment).

func HausdorffDistance

func HausdorffDistance(a, b Geometry) (float64, bool)

HausdorffDistance returns the discrete Hausdorff distance (planar) between the vertex sets of two geometries: the larger of the two directed distances.

func LengthMeters

func LengthMeters(g Geometry) float64

LengthMeters returns the geodesic length of all line components of g.

func LineIsSimple

func LineIsSimple(pts []Coord) bool

LineIsSimple reports whether a line's segments do not self-intersect except at shared endpoints of consecutive segments (and the closing point of a ring).

func PointInPolygon

func PointInPolygon(c Coord, p Polygon) int

PointInPolygon classifies c against polygon p: 1 = interior, 0 = on the boundary, -1 = exterior (including inside a hole).

func SegmentsIntersect

func SegmentsIntersect(p1, p2, p3, p4 Coord) bool

SegmentsIntersect reports whether segments p1-p2 and p3-p4 share any point, including collinear overlap and shared endpoints.

func SupportedSRID

func SupportedSRID(srid uint32) bool

SupportedSRID reports whether srid is one the computation kernels can handle.

func WKBFloat32ToStandard

func WKBFloat32ToStandard(b []byte) ([]byte, error)

WKBFloat32ToStandard converts a float32-coordinate WKB payload into a standard float64 WKB payload. ST_AsWKB / ST_AsBinary use this so a GEOMETRY32 value is always emitted as interoperable standard WKB.

func WriteGeoJSON

func WriteGeoJSON(g Geometry, maxDec int) string

WriteGeoJSON renders g as an RFC 7946 GeoJSON geometry object. When maxDec is >= 0 every coordinate is rounded to at most that many decimal places; a negative value keeps full round-trip precision.

func WriteWKB

func WriteWKB(g Geometry) []byte

WriteWKB encodes a Geometry as standard Well-Known Binary: little-endian (NDR), float64 coordinates, geometry type codes 1..7. The output is byte-compatible with PostGIS/MySQL ST_AsBinary and is what a GEOMETRY column stores verbatim in its varlena.

An empty point is encoded as POINT(NaN NaN); empty lines/polygons/collections are encoded with a zero element count.

func WriteWKBFloat32

func WriteWKBFloat32(g Geometry) []byte

WriteWKBFloat32 encodes a Geometry with float32 coordinates. This is the on-disk form of a GEOMETRY32 value.

func WriteWKT

func WriteWKT(g Geometry) string

WriteWKT renders a Geometry as Well-Known Text, matching MySQL's ST_AsText conventions: no space after the type keyword, no spaces after commas, the "<TYPE> EMPTY" form for empty geometries, and MULTIPOINT printed in the bare form "MULTIPOINT(1 1,2 2)".

Coordinates use the shortest decimal that round-trips to the same float64 (strconv 'g', -1), so WriteWKT(ParseWKT(x)) is stable.

Types

type BBox

type BBox struct {
	MinX, MinY, MaxX, MaxY float64
}

BBox is an axis-aligned bounding box.

func Envelope

func Envelope(g Geometry) (bb BBox, ok bool)

Envelope returns the bounding box of g. ok is false when g has no coordinates (empty geometry).

type BoolOp

type BoolOp int

BoolOp selects which Boolean operation overlay computes.

const (
	OpIntersection BoolOp = iota
	OpUnion
	OpDifference
	OpXOR
)

type Coord

type Coord struct {
	X, Y float64
}

Coord is a single 2D coordinate. The engine does not support Z (elevation) or M (measure) ordinates.

func Centroid

func Centroid(g Geometry) (Coord, bool)

Centroid returns the centroid of g using the OGC dimension rule: the centroid of the highest-dimension components present (areal, then linear, then puntal). ok is false for empty geometries.

type Geometry

type Geometry interface {
	// Type returns the concrete subtype (POINT, LINESTRING, ...).
	Type() Subtype
	// Empty reports whether the geometry holds no coordinates.
	Empty() bool
}

Geometry is implemented by every geometry kind in the model.

func Buffer

func Buffer(g Geometry, dist float64, quadSegs int) (Geometry, error)

Buffer returns the set of points within dist of g, computed as the union of discs at every vertex, rectangles along every edge, and the original areal part. quadSegs controls the disc approximation (segments per quarter circle). Only non-negative distances are supported.

func Collect

func Collect(gs ...Geometry) Geometry

Collect combines geometries into the most specific aggregate: a MultiPoint, MultiLineString, or MultiPolygon when every atomic part shares one kind, or a GeometryCollection otherwise. Nested multis and collections are flattened into their atomic parts first.

func ConvexHull

func ConvexHull(g Geometry) Geometry

ConvexHull returns the convex hull of every coordinate in g: a Polygon when the points span an area, a LineString when they are collinear (2+ distinct points), a Point for a single distinct point, or POINT EMPTY when g has no coordinates. Computed with Andrew's monotone-chain algorithm (planar).

func InterpolatePoints

func InterpolatePoints(l LineString, f float64) (Geometry, error)

InterpolatePoints returns points placed at every multiple of fraction f along the line (always including the 100% endpoint). A single resulting point is returned as a Point, otherwise as a MultiPoint.

func Overlay

func Overlay(a, b Geometry, op BoolOp) (Geometry, error)

Overlay computes a Boolean operation between two areal geometries.

func ParseGeoJSON

func ParseGeoJSON(data []byte) (Geometry, error)

ParseGeoJSON decodes an RFC 7946 GeoJSON geometry object. Feature and FeatureCollection objects are not geometries and are rejected.

func ParseWKT

func ParseWKT(s string) (Geometry, error)

ParseWKT parses a Well-Known Text representation into a Geometry. It accepts all seven geometry kinds, the "<TYPE> EMPTY" forms, and nested GEOMETRYCOLLECTION. Parsing is case-insensitive and whitespace-tolerant.

Only 2D geometries are supported; a Z (elevation) or M (measure) ordinate is rejected (per gis.md, POINTZ/POINTM and friends are out of scope).

func ReadWKB

func ReadWKB(b []byte) (Geometry, error)

ReadWKB decodes standard Well-Known Binary (float64 coordinates) into a Geometry. Each (sub-)geometry's byte order is honored independently, so both little-endian (NDR) and big-endian (XDR) input are accepted. Only 2D type codes 1..7 are supported; Z/M or EWKB-flagged codes are rejected.

func ReadWKBFloat32

func ReadWKBFloat32(b []byte) (Geometry, error)

ReadWKBFloat32 decodes float32-coordinate WKB (the GEOMETRY32 storage form) into a Geometry whose coordinates are the float32 values widened to float64.

func Simplify

func Simplify(g Geometry, tol float64) Geometry

Simplify returns g with its vertices reduced using the Ramer-Douglas-Peucker algorithm with the given distance tolerance (planar units). Points and multipoints are returned unchanged. Rings that would degenerate below a triangle are kept as-is so polygons stay valid.

func SwapXY

func SwapXY(g Geometry) Geometry

SwapXY returns a copy of g with the X and Y of every coordinate swapped (ST_SwapXY).

type GeometryCollection

type GeometryCollection struct {
	Geometries []Geometry
}

GeometryCollection is a heterogeneous collection of geometries, which may itself contain nested collections.

func (GeometryCollection) Empty

func (g GeometryCollection) Empty() bool

func (GeometryCollection) Type

func (GeometryCollection) Type() Subtype

type LineString

type LineString struct {
	Points []Coord
}

LineString is an ordered sequence of two or more coordinates (or zero, when empty).

func (LineString) Closed

func (l LineString) Closed() bool

Closed reports whether the line's first and last coordinates coincide. An empty line is not closed.

func (LineString) Empty

func (l LineString) Empty() bool

func (LineString) Type

func (LineString) Type() Subtype

type MultiLineString

type MultiLineString struct {
	Lines []LineString
}

MultiLineString is a collection of line strings.

func (MultiLineString) Empty

func (m MultiLineString) Empty() bool

func (MultiLineString) Type

func (MultiLineString) Type() Subtype

type MultiPoint

type MultiPoint struct {
	Points []Point
}

MultiPoint is a collection of points.

func (MultiPoint) Empty

func (m MultiPoint) Empty() bool

func (MultiPoint) Type

func (MultiPoint) Type() Subtype

type MultiPolygon

type MultiPolygon struct {
	Polygons []Polygon
}

MultiPolygon is a collection of polygons.

func (MultiPolygon) Empty

func (m MultiPolygon) Empty() bool

func (MultiPolygon) Type

func (MultiPolygon) Type() Subtype

type Point

type Point struct {
	X, Y    float64
	IsEmpty bool
}

Point is a single location. An empty point (POINT EMPTY) carries no coordinate; its X/Y are ignored when IsEmpty is true.

func InterpolatePoint

func InterpolatePoint(l LineString, f float64) (Point, error)

InterpolatePoint returns the point at fraction f (0..1) of a line's total Cartesian length. Values outside [0,1] are clamped.

func PointAtDistance

func PointAtDistance(l LineString, dist float64) (Point, error)

PointAtDistance returns the point reached after travelling dist Cartesian units along the line. dist must lie within [0, length].

func (Point) Coord

func (p Point) Coord() Coord

func (Point) Empty

func (p Point) Empty() bool

func (Point) Type

func (Point) Type() Subtype

type Polygon

type Polygon struct {
	Rings [][]Coord
}

Polygon is a set of linear rings. Rings[0] is the exterior ring and any further entries are interior rings (holes). Each ring is a closed sequence of coordinates (first == last).

func (Polygon) Empty

func (p Polygon) Empty() bool

func (Polygon) Type

func (Polygon) Type() Subtype

type Subtype

type Subtype uint8

Subtype identifies the kind of a geometry. The values match the standard WKB geometry-type codes for the seven concrete kinds (1..7); GENERIC (0) is the unconstrained "any geometry" used for a plain GEOMETRY column.

The SQL layer stores this value in types.Type.Scale.

const (
	GENERIC            Subtype = 0
	POINT              Subtype = 1
	LINESTRING         Subtype = 2
	POLYGON            Subtype = 3
	MULTIPOINT         Subtype = 4
	MULTILINESTRING    Subtype = 5
	MULTIPOLYGON       Subtype = 6
	GEOMETRYCOLLECTION Subtype = 7
)

func (Subtype) String

func (s Subtype) String() string

String returns the canonical WKT keyword for the subtype. GENERIC maps to "GEOMETRY".

func (Subtype) Valid

func (s Subtype) Valid() bool

Valid reports whether s is one of the eight known subtypes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL