geometry

package
v0.2.21 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package geometry provides 2D geometry primitives (Point, LineString, Polygon, MultiPoint) with WKB and WKT encoding, a coordinate reference system model, and common spatial operations (area, distance, centroid, convex hull, intersection tests).

All coordinates are 2D. XY order (X = longitude/easting, Y = latitude/northing) matches the WKB, WKT, and GeoJSON specifications. Angles are always in degrees at the API surface; internal trig uses radians.

Index

Constants

View Source
const DefaultBufferSegments = 32

DefaultBufferSegments is the number of straight segments used to approximate a full circle in Buffer operations when the caller doesn't specify one.

View Source
const EarthRadiusKM = 6371.0088

EarthRadiusKM is the mean Earth radius used by haversine calculations.

View Source
const RTreeNodeSize = 16

RTreeNodeSize is the maximum number of children in an R-tree node. Values around 16 balance memory density and traversal cost.

Variables

View Source
var (
	WGS84          = CRS{EPSG: 4326, Name: "WGS 84", Projected: false}
	PseudoMercator = CRS{EPSG: 3857, Name: "WGS 84 / Pseudo-Mercator", Projected: true}
)

Known CRSes. The set is intentionally small; add as needed.

View Source
var (
	ErrShortWKB          = errors.New("geometry: WKB too short")
	ErrInvalidByteOrder  = errors.New("geometry: invalid WKB byte order")
	ErrUnsupportedWKB    = errors.New("geometry: unsupported WKB geometry type")
	ErrTypeMismatch      = errors.New("geometry: WKB type does not match target")
	ErrEmptyGeometry     = errors.New("geometry: geometry has no points")
	ErrInvalidWKT        = errors.New("geometry: invalid WKT")
	ErrUnknownCRS        = errors.New("geometry: unknown CRS")
	ErrInvalidUnit       = errors.New("geometry: invalid distance unit")
	ErrCRSMismatch       = errors.New("geometry: operation requires geometries in the same CRS")
	ErrProjectionMissing = errors.New("geometry: reprojection between these CRSes is not implemented")
)

Functions

func Area

func Area(g Geometry, u Unit) (float64, error)

Area returns the planar (XY) area of g in u². Non-polygonal geometries return 0.

func Contains

func Contains(a, b Geometry) bool

Contains reports whether a fully contains b.

func Euclidean

func Euclidean(from, to Point, u Unit) (float64, error)

Euclidean returns the planar distance between two Points, in the requested unit. The input coordinates are assumed to already be in meters (projected CRS); Z / CRS are ignored.

Breaking change in v0.2.16: previously took four float64 args (x1, y1, x2, y2). The new signature aligns with Haversine + HaversineBatch + Point.Distance. Migration: replace `Euclidean(a.X, a.Y, b.X, b.Y, u)` with `Euclidean(a, b, u)`.

func Haversine

func Haversine(from, to Point, u Unit) (float64, error)

Haversine returns the great-circle distance between two lon/lat Points on a sphere of Earth radius, in the requested unit. Point X = longitude, Y = latitude (WKB convention); Z / CRS are ignored.

Breaking change in v0.2.16: previously took four float64 args (lon1, lat1, lon2, lat2). The new signature aligns with HaversineBatch and Point.Distance so callers holding geometry types can pass them directly. Migration: replace `Haversine(a.X, a.Y, b.X, b.Y, u)` with `Haversine(a, b, u)`.

func HaversineBatch added in v0.2.16

func HaversineBatch(from, to []Point, u Unit) ([]float64, error)

HaversineBatch returns per-pair great-circle distances between from[i] and to[i] in the requested unit. Semantically equivalent to calling Haversine(from[i], to[i], u) in a loop, but bulk-optimized:

  • The unit conversion factor, Earth-radius constant, and degree-to-radian scale are hoisted outside the inner loop (one metersPerUnit call for the whole batch).
  • Per-row math runs in a fixed-count vars body — Go's inliner keeps it tight vs. the per-call scalar Haversine which pays a function-call boundary + defer + err-check per row.

Both input slices must be the same length; a mismatch returns ErrColumnLenMismatch. Empty slices are legal and return an empty (non-nil) result.

CRS on each Point is ignored — Haversine is a lon/lat sphere computation that expects Y=latitude, X=longitude in degrees. Points in a projected CRS give nonsensical distances; converting via ToCRS(WGS84) before calling is the caller's responsibility.

Return type is a flat []float64 — same shape a downstream SIMD kernel or arrow builder wants. Nulls in the input aren't signaled (Point isn't a nullable type); to skip-and-preserve row positions, either pre-filter or pass sentinel points and mask the output.

func Intersects

func Intersects(a, b Geometry) bool

Intersects reports whether a and b share any point. The relation is symmetric.

func Length

func Length(g Geometry, u Unit) (float64, error)

Length returns the planar (XY) length of g in u. Non-linear geometries (Point, MultiPoint, Polygon) return 0. Polygons don't return perimeter here — use Polygon.Perimeter for that.

func MetersPerUnit added in v0.2.16

func MetersPerUnit(u Unit) (float64, error)

MetersPerUnit returns the number of meters in one of the given unit. Exported so callers building their own bulk distance kernels can hoist the scale factor outside a hot loop instead of paying a per-call `metersPerUnit` lookup.

func RegisterCRS

func RegisterCRS(c CRS)

RegisterCRS adds a CRS to the runtime registry. Overwrites any prior entry for the same EPSG code.

func String

func String(g Geometry) string

String returns g's WKT representation, prefixed by its CRS if set.

func Test

func Test(pred Predicate, a, b Geometry) bool

Test evaluates pred on the ordered pair (a, b).

func UTMEpsgFor

func UTMEpsgFor(lon, lat float64) int32

UTMEpsgFor returns the EPSG code of the UTM CRS covering (lon, lat) on the WGS84 datum. Latitude sign selects hemisphere.

func UTMZoneFor

func UTMZoneFor(lon float64) int

UTMZoneFor returns the UTM zone number [1..60] whose central meridian nearest longitude lon.

func WKB

func WKB(g Geometry) []byte

WKB returns the Well-Known Binary encoding of g.

func Within

func Within(a, b Geometry) bool

Within is Contains(b, a).

Types

type Bounds

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

Bounds is an axis-aligned 2D bounding box: (MinX, MinY, MaxX, MaxY).

func EmptyBounds

func EmptyBounds() Bounds

EmptyBounds returns a bounds value that will always be extended by the first point passed to Extend.

func (Bounds) Contains

func (b Bounds) Contains(x, y float64) bool

Contains reports whether the bounds contain (x, y). The upper edges are inclusive.

func (Bounds) Empty

func (b Bounds) Empty() bool

Empty reports whether the bounds are the zero-extent inverted sentinel.

func (Bounds) Extend

func (b Bounds) Extend(x, y float64) Bounds

Extend returns a Bounds enlarged to include (x, y).

func (Bounds) Intersects

func (b Bounds) Intersects(o Bounds) bool

Intersects reports whether the two bounds overlap.

func (Bounds) Union

func (b Bounds) Union(o Bounds) Bounds

Union returns the smallest Bounds containing both b and o.

type BufferOptions

type BufferOptions struct {
	// Segments controls the number of straight edges used to approximate a
	// full circle. Higher = smoother, larger output. 0 falls back to
	// DefaultBufferSegments.
	Segments int
}

BufferOptions configures Buffer behavior.

type CRS

type CRS struct {
	EPSG      int32
	Name      string
	Projected bool
}

CRS identifies a coordinate reference system. Only EPSG code is authoritative for equality — Name is a human-readable label.

func LookupCRS

func LookupCRS(epsg int32) (CRS, error)

LookupCRS returns the CRS for the given EPSG code, or ErrUnknownCRS.

func (CRS) Equal

func (c CRS) Equal(o CRS) bool

Equal reports whether two CRSes refer to the same system.

func (CRS) String

func (c CRS) String() string

func (CRS) Zero

func (c CRS) Zero() bool

Zero reports whether the CRS is the zero value.

type Geometry

type Geometry interface {
	// Type returns the concrete geometry type.
	Type() Type
	// CRS returns the coordinate reference system.
	CRS() CRS
	// Bounds returns the axis-aligned bounding box (minX, minY, maxX, maxY).
	Bounds() Bounds
	// Is3D reports whether the geometry carries Z (XYZ). Bounds and 2D
	// operations ignore Z whether or not the geometry is 3D.
	Is3D() bool
	// Centroid returns the geometry's centroid using its type-specific
	// definition. For Point this is the identity; for lines, polygons,
	// and collections see the concrete implementations.
	Centroid() Point
	// WKT returns the Well-Known Text representation.
	WKT() string
	// AppendWKB appends the little-endian WKB encoding to buf and returns
	// the resulting slice.
	AppendWKB(buf []byte) []byte
}

Geometry is the common interface for all geometry primitives.

func Buffer

func Buffer(g Geometry, distance float64, opts BufferOptions) (Geometry, error)

Buffer returns a polygon (or MultiPolygon-shaped result) approximating the set of points within distance of g, using rounded joins and caps.

Only positive distances are supported. Passing distance <= 0 returns (nil, error). Buffering Polygon inputs assumes the input's exterior ring is convex or nearly so; strongly concave inputs may produce self- intersecting output rings (see file-level comment).

func ParseWKB

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

ParseWKB decodes a Well-Known Binary geometry. The resulting geometry has no CRS set; callers must supply one from context (e.g. a GeoParquet schema).

func ParseWKT

func ParseWKT(s string) (Geometry, error)

ParseWKT parses a Well-Known Text geometry. Whitespace and case around the type keyword are tolerated; a " Z" qualifier after the keyword (e.g. "POINT Z (1 2 3)") switches the parser into 3D mode. Coordinates must be numeric.

func Project

func Project(g Geometry, target CRS) (Geometry, error)

Project reprojects g from its current CRS to target. If the source or target CRS is unset, WGS84 is assumed. Supported source/target pairs:

  • WGS84 (EPSG:4326) ↔ Web Mercator (EPSG:3857)
  • WGS84 (EPSG:4326) ↔ UTM zone (EPSG:32601–32660 / 32701–32760)

Other pairs (Mercator ↔ UTM, UTM ↔ UTM) are routed through WGS84 internally.

func Simplify

func Simplify(g Geometry, tolerance float64) (Geometry, error)

Simplify returns a copy of g with vertices removed until every discarded vertex lies within tolerance (planar distance) of the retained polyline. Uses the Douglas-Peucker algorithm.

tolerance is measured in the CRS's linear unit (degrees for WGS84, meters for a projected CRS). Passing tolerance <= 0 returns g unchanged.

Point and MultiPoint pass through untouched; the algorithm doesn't apply to them. GeometryCollection recurses into each component.

type GeometryCollection

type GeometryCollection struct {
	Geometries []Geometry
	CRSValue   CRS
	HasZ       bool
}

GeometryCollection is a heterogeneous set of geometries. Per the OGC spec and PostGIS's practical guarantee, a GeometryCollection may not directly contain another GeometryCollection. Setting HasZ marks the collection as 3D; each contained geometry is expected to share that dimensionality.

func NewGeometryCollection

func NewGeometryCollection(gs []Geometry, crs CRS) GeometryCollection

NewGeometryCollection returns a 2D GeometryCollection wrapping the given geometries.

func NewGeometryCollectionZ

func NewGeometryCollectionZ(gs []Geometry, crs CRS) GeometryCollection

NewGeometryCollectionZ returns a 3D GeometryCollection.

func (GeometryCollection) AppendWKB

func (c GeometryCollection) AppendWKB(buf []byte) []byte

func (GeometryCollection) Bounds

func (c GeometryCollection) Bounds() Bounds

func (GeometryCollection) CRS

func (c GeometryCollection) CRS() CRS

func (GeometryCollection) Centroid

func (c GeometryCollection) Centroid() Point

Centroid returns the midpoint of the collection's overall bounding box. A meaningful centroid for a heterogeneous collection is not universally defined; the bounds midpoint is a stable, cheap approximation.

func (GeometryCollection) EstimateUTMCRS

func (c GeometryCollection) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering the collection's bounds midpoint.

func (GeometryCollection) Is3D

func (c GeometryCollection) Is3D() bool

func (GeometryCollection) Type

func (c GeometryCollection) Type() Type

func (GeometryCollection) WKT

func (c GeometryCollection) WKT() string

type LineString

type LineString struct {
	Points   []Point
	CRSValue CRS
	HasZ     bool
}

LineString is an ordered sequence of two or more points. Set HasZ to true to encode Z values in WKB/WKT output.

func NewLineString

func NewLineString(pts []Point, crs CRS) LineString

NewLineString returns a 2D LineString sharing the underlying slice.

func NewLineStringZ

func NewLineStringZ(pts []Point, crs CRS) LineString

NewLineStringZ returns a 3D LineString.

func (LineString) AppendWKB

func (l LineString) AppendWKB(buf []byte) []byte

func (LineString) Bounds

func (l LineString) Bounds() Bounds

Bounds returns the XY bounding box. Z is ignored.

func (LineString) Buffer

func (l LineString) Buffer(distance float64, segments int) Polygon

Buffer returns a polygon approximating the set of points within distance of the linestring, using rounded joins at internal vertices and rounded caps at the endpoints. Requires the linestring to have at least 2 points.

func (LineString) CRS

func (l LineString) CRS() CRS

func (LineString) Centroid

func (l LineString) Centroid() Point

Centroid returns the length-weighted midpoint of the linestring in planar XY. Each segment contributes its midpoint weighted by its planar length; the result carries l's CRS.

func (LineString) EstimateUTMCRS

func (l LineString) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering the linestring's bounds midpoint. If the linestring is in a projected CRS, the midpoint is inverse-projected to WGS84 first.

func (LineString) Is3D

func (l LineString) Is3D() bool

func (LineString) Length

func (l LineString) Length(u Unit) (float64, error)

Length returns the total planar (XY) length of the linestring in the requested unit. Z is ignored. Geographic CRSes use haversine; projected CRSes use planar distance.

func (LineString) Simplify

func (l LineString) Simplify(tolerance float64) LineString

Simplify returns a copy of l with vertices removed via Douglas-Peucker at the given planar tolerance. Endpoints are always preserved. If the line has fewer than 3 points it is returned unchanged (a 2-point line is already the simplest possible representation).

func (LineString) ToCRS

func (l LineString) ToCRS(target CRS) (LineString, error)

ToCRS reprojects the linestring into target.

func (LineString) Type

func (l LineString) Type() Type

func (LineString) WKT

func (l LineString) WKT() string

type MultiLineString

type MultiLineString struct {
	Lines    []LineString
	CRSValue CRS
	HasZ     bool
}

MultiLineString is a collection of LineStrings.

func NewMultiLineString

func NewMultiLineString(lines []LineString, crs CRS) MultiLineString

NewMultiLineString returns a 2D MultiLineString wrapping lines.

func NewMultiLineStringZ

func NewMultiLineStringZ(lines []LineString, crs CRS) MultiLineString

NewMultiLineStringZ returns a 3D MultiLineString.

func (MultiLineString) AppendWKB

func (m MultiLineString) AppendWKB(buf []byte) []byte

func (MultiLineString) Bounds

func (m MultiLineString) Bounds() Bounds

func (MultiLineString) CRS

func (m MultiLineString) CRS() CRS

func (MultiLineString) Centroid

func (m MultiLineString) Centroid() Point

Centroid returns the length-weighted centroid of the multi-linestring, where each component contributes its centroid weighted by its planar length. Empty geometry returns the zero Point.

func (MultiLineString) EstimateUTMCRS

func (m MultiLineString) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering the multiline's bounds midpoint.

func (MultiLineString) Is3D

func (m MultiLineString) Is3D() bool

func (MultiLineString) Length

func (m MultiLineString) Length(u Unit) (float64, error)

Length sums the length of every line in the requested unit (XY only).

func (MultiLineString) Type

func (m MultiLineString) Type() Type

func (MultiLineString) WKT

func (m MultiLineString) WKT() string

type MultiPoint

type MultiPoint struct {
	Points   []Point
	CRSValue CRS
	HasZ     bool
}

MultiPoint is an unordered collection of points. Set HasZ to true to encode Z on WKB/WKT output.

func NewMultiPoint

func NewMultiPoint(pts []Point, crs CRS) MultiPoint

func NewMultiPointZ

func NewMultiPointZ(pts []Point, crs CRS) MultiPoint

func (MultiPoint) AppendWKB

func (m MultiPoint) AppendWKB(buf []byte) []byte

func (MultiPoint) Bounds

func (m MultiPoint) Bounds() Bounds

func (MultiPoint) CRS

func (m MultiPoint) CRS() CRS

func (MultiPoint) Centroid

func (m MultiPoint) Centroid() Point

Centroid returns the arithmetic mean of the multipoint's points.

func (MultiPoint) EstimateUTMCRS

func (m MultiPoint) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering the multipoint's bounds midpoint.

func (MultiPoint) Is3D

func (m MultiPoint) Is3D() bool

func (MultiPoint) Type

func (m MultiPoint) Type() Type

func (MultiPoint) WKT

func (m MultiPoint) WKT() string

type MultiPolygon

type MultiPolygon struct {
	Polygons []Polygon
	CRSValue CRS
	HasZ     bool
}

MultiPolygon is a collection of Polygons.

func NewMultiPolygon

func NewMultiPolygon(polys []Polygon, crs CRS) MultiPolygon

NewMultiPolygon returns a 2D MultiPolygon wrapping polys.

func NewMultiPolygonZ

func NewMultiPolygonZ(polys []Polygon, crs CRS) MultiPolygon

NewMultiPolygonZ returns a 3D MultiPolygon.

func (MultiPolygon) AppendWKB

func (m MultiPolygon) AppendWKB(buf []byte) []byte

func (MultiPolygon) Area

func (m MultiPolygon) Area(u Unit) (float64, error)

Area sums the planar (XY) area of every component polygon in u².

func (MultiPolygon) Bounds

func (m MultiPolygon) Bounds() Bounds

func (MultiPolygon) CRS

func (m MultiPolygon) CRS() CRS

func (MultiPolygon) Centroid

func (m MultiPolygon) Centroid() Point

Centroid returns the area-weighted centroid of the multipolygon. Each component contributes its own centroid weighted by its planar area (or spherical area for geographic CRSes). Empty geometry returns the zero Point.

func (MultiPolygon) Contains

func (m MultiPolygon) Contains(pt Point) bool

Contains reports whether pt lies inside any polygon in the collection.

func (MultiPolygon) EstimateUTMCRS

func (m MultiPolygon) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering the multipolygon's bounds midpoint.

func (MultiPolygon) Is3D

func (m MultiPolygon) Is3D() bool

func (MultiPolygon) Type

func (m MultiPolygon) Type() Type

func (MultiPolygon) WKT

func (m MultiPolygon) WKT() string

type Point

type Point struct {
	X, Y, Z  float64
	CRSValue CRS
	HasZ     bool
}

Point is a 2D or optionally 3D (XYZ) point. Z is populated only when HasZ is true; otherwise it is ignored by encoders and decoders.

func Centroid

func Centroid(g Geometry) Point

Centroid returns the centroid of g using each concrete type's own definition. Kept as a package-level helper for API symmetry with Area and Length; internally this is just interface dispatch on g.Centroid().

func NewPoint

func NewPoint(x, y float64, crs CRS) Point

NewPoint returns a 2D Point with the given coordinates and CRS. Passing the zero CRS leaves the CRS unset (interpreted as WGS84 by most operations).

func NewPointZ

func NewPointZ(x, y, z float64, crs CRS) Point

NewPointZ returns a 3D Point (X, Y, Z) with the given CRS.

func (Point) AppendWKB

func (p Point) AppendWKB(buf []byte) []byte

func (Point) Bounds

func (p Point) Bounds() Bounds

Bounds returns the XY bounding box. Z, if present, is ignored (the Bounds type is deliberately 2D).

func (Point) Buffer

func (p Point) Buffer(distance float64, segments int) Polygon

Buffer returns a circular polygon of radius distance centered on p, approximated with the given number of edge segments. segments < 4 falls back to DefaultBufferSegments.

func (Point) CRS

func (p Point) CRS() CRS

func (Point) Centroid

func (p Point) Centroid() Point

Centroid returns p itself — a Point is its own centroid. Present so Point satisfies the Geometry interface's Centroid method and the top-level geometry.Centroid dispatch collapses to interface dispatch.

func (Point) Distance

func (p Point) Distance(o Point, u Unit) (float64, error)

Distance returns the planar (XY) distance from p to o in the requested unit. Z is ignored. For geographic CRSes Haversine is used; for projected CRSes Euclidean.

func (Point) Distance3D

func (p Point) Distance3D(o Point, u Unit) (float64, error)

Distance3D returns the 3D Euclidean distance from p to o, treating Z as coplanar with X/Y (i.e. as if measured in the same unit as the CRS's linear unit). Requires both points to be in the same projected CRS and to have HasZ set on both sides; otherwise returns ErrCRSMismatch or an error noting the missing dimension.

func (Point) Equal

func (p Point) Equal(o Point) bool

Equal reports whether p and o are equal in coordinates, CRS, and dimensionality. Z is compared only if both points are 3D.

func (Point) EstimateUTMCRS

func (p Point) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering p (on the WGS84 datum). If p is in a projected CRS, it is first inverse-projected to WGS84 to pick the zone.

func (Point) Is3D

func (p Point) Is3D() bool

func (Point) ToCRS

func (p Point) ToCRS(target CRS) (Point, error)

ToCRS reprojects p into target. Z is carried through unchanged.

func (Point) Type

func (p Point) Type() Type

func (Point) WKT

func (p Point) WKT() string

type Polygon

type Polygon struct {
	Rings    [][]Point
	CRSValue CRS
	HasZ     bool
}

Polygon is a planar surface defined by one exterior linear ring and zero or more interior rings (holes). Rings are lists of points; the first and last point of each ring must coincide (Polygon operations close rings implicitly if they don't).

func NewPolygon

func NewPolygon(rings [][]Point, crs CRS) Polygon

NewPolygon returns a 2D Polygon with the given rings. The first ring is the exterior boundary; any subsequent rings are holes.

func NewPolygonZ

func NewPolygonZ(rings [][]Point, crs CRS) Polygon

NewPolygonZ returns a 3D Polygon.

func SimplePolygon

func SimplePolygon(exterior []Point, crs CRS) Polygon

SimplePolygon returns a Polygon with a single exterior ring.

func (Polygon) AppendWKB

func (p Polygon) AppendWKB(buf []byte) []byte

func (Polygon) Area

func (p Polygon) Area(u Unit) (float64, error)

Area returns the polygon area. For geographic CRSes the area is computed on a sphere of Earth radius and returned in u² (u ∈ km/mi/nmi/m/ft). For projected CRSes the area is planar (signed absolute value) in the CRS's linear unit², converted to u².

func (Polygon) Bounds

func (p Polygon) Bounds() Bounds

func (Polygon) Buffer

func (p Polygon) Buffer(distance float64, segments int) Polygon

Buffer returns a polygon approximating the set of points within distance of p's exterior ring. Holes are shrunk (their offset ring moves inward); if a hole's offset would collapse or self-intersect it is dropped.

This is a positive (outward) buffer only. For convex or nearly-convex inputs the output is topologically correct. For strongly concave inputs the offset exterior ring may self-intersect — cleaning that up requires a polygon-union pass, which this package doesn't yet provide.

func (Polygon) CRS

func (p Polygon) CRS() CRS

func (Polygon) Centroid

func (p Polygon) Centroid() Point

Centroid returns the area-weighted centroid of the exterior ring, using the planar (shoelace) formula. For small geographic polygons the result is a close approximation.

func (Polygon) Contains

func (p Polygon) Contains(pt Point) bool

Contains reports whether pt lies inside p (exterior ring, minus any holes). The check uses the winding-parity (crossing) rule. Points on the boundary have undefined containment.

func (Polygon) ConvexHull

func (p Polygon) ConvexHull() Polygon

ConvexHull returns the convex hull of the polygon's exterior points using the Graham scan. Points on collinear edges are dropped.

func (Polygon) EstimateUTMCRS

func (p Polygon) EstimateUTMCRS() (CRS, error)

EstimateUTMCRS returns the CRS of the UTM zone covering the polygon's centroid. If the polygon is in a projected CRS, the centroid is inverse-projected to WGS84 first.

func (Polygon) Exterior

func (p Polygon) Exterior() []Point

Exterior returns the exterior ring, or nil if the polygon has no rings.

func (Polygon) Is3D

func (p Polygon) Is3D() bool

func (Polygon) Perimeter

func (p Polygon) Perimeter(u Unit) (float64, error)

Perimeter returns the length of the polygon's exterior ring in u.

func (Polygon) Simplify

func (p Polygon) Simplify(tolerance float64) Polygon

Simplify applies Douglas-Peucker to each ring of the polygon. Rings that collapse to fewer than 4 points (three unique vertices plus the closing vertex) are kept as-is to preserve topological validity of the polygon.

func (Polygon) ToCRS

func (p Polygon) ToCRS(target CRS) (Polygon, error)

ToCRS reprojects the polygon into target.

func (Polygon) Type

func (p Polygon) Type() Type

func (Polygon) WKT

func (p Polygon) WKT() string

type Predicate

type Predicate uint8

Predicate names a binary spatial predicate.

const (
	// PredIntersects: a and b share any point.
	PredIntersects Predicate = iota
	// PredContains: a fully contains b (every point of b lies in a).
	PredContains
	// PredWithin: a lies fully within b (equivalent to Contains(b, a)).
	PredWithin
)

func (Predicate) String

func (p Predicate) String() string

type RTree

type RTree struct {
	// contains filtered or unexported fields
}

RTree is a static, bulk-loaded Sort-Tile-Recursive R-tree over 2D bounding boxes. Once built with NewRTree the tree is immutable and safe for concurrent readers.

func NewRTree

func NewRTree(bounds []Bounds) *RTree

NewRTree builds an R-tree over the given bounding boxes. Item IDs returned by queries are indexes into bounds.

func (*RTree) Bounds

func (t *RTree) Bounds() Bounds

Bounds returns the R-tree's overall bounding box.

func (*RTree) Len

func (t *RTree) Len() int

Len returns the number of items indexed.

func (*RTree) Nearest

func (t *RTree) Nearest(x, y float64, k int) []int32

Nearest returns the k item IDs whose bounding boxes are closest (by squared Euclidean point-to-bbox distance) to (x, y), in ascending distance order. Fewer than k IDs are returned if the tree is smaller.

For the k=1 case, prefer NearestOne — same semantics but skips the priority queue for a zero-allocation depth-first descent.

func (*RTree) NearestOne added in v0.2.17

func (t *RTree) NearestOne(x, y float64) (id int32, ok bool)

NearestOne returns the ID of the item whose bounding box is closest to (x, y) by squared Euclidean point-to-bbox distance. ok=false when the tree is empty. Semantically equivalent to Nearest(x, y, 1)[0] but with zero allocations — depth-first descent with a running best-so-far distance + bbox pruning replaces the general k>1 path's priority queue.

Callers doing a single-nearest lookup at high frequency (e.g. snap-to-graph, per-point classification) should prefer this over Nearest(x, y, 1). At 1M+ calls per request the alloc + boxing savings dominate the CPU profile.

func (*RTree) Search

func (t *RTree) Search(q Bounds) []int32

Search returns the IDs of every item whose bounding box intersects q. Allocates a fresh result slice per call.

func (*RTree) SearchInto

func (t *RTree) SearchInto(buf []int32, q Bounds) []int32

SearchInto appends every item ID whose bounding box intersects q to buf (after truncating buf to zero length) and returns the resulting slice. This lets callers reuse a scratch buffer across queries to avoid a fresh allocation each time.

type Type

type Type uint8

Type identifies a geometry kind.

const (
	TypeUnknown Type = iota
	TypePoint
	TypeLineString
	TypePolygon
	TypeMultiPoint
	TypeMultiLineString
	TypeMultiPolygon
	TypeGeometryCollection
)

func (Type) String

func (t Type) String() string

type Unit

type Unit string

Unit represents a linear distance unit.

const (
	UnitMeters        Unit = "m"
	UnitKilometers    Unit = "km"
	UnitMiles         Unit = "mi"
	UnitFeet          Unit = "ft"
	UnitNauticalMiles Unit = "nmi"
)

Jump to

Keyboard shortcuts

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