📚 simplefeatures - Awesome Go Library for Geographic

Go Gopher mascot for simplefeatures

simplesfeatures is a 2D geometry library that provides Go types that model geometries, as well as algorithms that operate on them.

🏷️ Geographic
📂 Geographic tools and servers
130 stars
View on GitHub 🔗

Detailed Description of simplefeatures

Simple Features

Documentation Build Status Go Report
Card Coverage
Status

Simple Features is a 2D geometry library that provides Go types that model geometries, as well as algorithms that operate on them.

It's a pure Go Implementation of the OpenGIS Consortium's Simple Feature Access Specification (which can be found here). This is the same specification that GEOS, JTS, and PostGIS implement, so the Simple Features API will be familiar to developers who have used those libraries before.

Table of Contents

Geometry Types

TypeExampleDescription
PointPoint is a single location in space.
MultiPointMultiPoint is collection of points in space.
LineStringLineString is curve defined by linear interpolation between a set of control points.
MultiLineStringMultiLineString is a collection of LineStrings.
PolygonPolygon is a planar surface geometry that bounds some area. It may have holes.
MultiPolygonMultiPolygon is collection of Polygons (with some constraints on how the Polygons interact with each other).
GeometryCollectionGeometryCollection is an unconstrained collection of geometries.
GeometryGeometry holds any type of geometry (Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, or GeometryCollection). It's the type that the Simple Features library uses when it needs to represent geometries in a generic way.
EnvelopeEnvelope is an axis aligned bounding box typically used to describe the spatial extent of other geometric entities.

Marshalling and Unmarshalling

Simple features supports the following external geometry representation formats:

FormatExampleDescription
WKTPOLYGON((0 0,0 1,1 1,1 0,0 0))Well Known Text is a human readable format for storing geometries. It's often the lowest common denominator geometry format, and is useful for integration with other GIS applications.
WKB<binary>Well Known Binary is a machine readable format that is efficient for computers to use (both from a processing and storage space perspective). WKB is a good choice for transferring geometries to and from PostGIS and other databases that support geometric types.
GeoJSON{"type":"Polygon","coordinates":[[[0,0],[0,1],[1,1],[1,0],[0,0]]]}GeoJSON represents geometries in a similar way to WKB, but is based on the JSON format. This makes it ideal to use with web APIs or other situations where JSON would normally be used.
TWKB<binary>Tiny Well Known Binary is a multi-purpose compressed binary format for serialising vector geometries into a stream of bytes. It emphasises minimising the size of the serialised representation. It's a good choice when space is at a premium (e.g. for storage within a web token).

Geometry Algorithms

The following algorithms are supported:

Miscellaneous AlgorithmsDescription
AreaFinds the area of the geometry (for Polygons and MultiPolygons).
CentroidFinds the centroid of the geometry.
ConvexHullFinds the convex hull of the geometry.
DistanceFinds the shortest distance between two geometries.
EnvelopeFinds the smallest axis-aligned bounding-box that surrounds the geometry.
ExactEqualsDetermines if two geometries are structurally equal.
LengthFinds the length of the geometry (for LineStrings and MultiLineStrings).
PointOnSurfaceFinds a point that lies inside the geometry.
RelateCalculates the DE-9IM intersection describing the relationship between two geometries.
SimplifySimplifies a geometry using the Ramer–Douglas–Peucker algorithm.
Set OperationsDescription
UnionJoins the parts from two geometries together.
IntersectionFinds the parts of two geometries that are in common.
DifferenceFinds the parts of a geometry that are not also part of another geometry.
SymmetricDifferenceFinds the parts of two geometries that are not in common.
Named Spatial PredicatesDescription
EqualsDetermines if two geometries are topologically equal.
IntersectsDetermines if two geometries intersect with each other.
DisjointDetermines if two geometries have no common points.
ContainsDetermines if one geometry contains another.
CoveredByDetermines if one geometry is covered by another.
CoversDetermines if one geometry covers another.
OverlapsDetermines if one geometry overlaps another.
TouchesDetermines if one geometry touches another.
WithinDetermines if one geometry is within another.
CrossesDetermines if one geometry crosses another.

GEOS Wrapper

A GEOS CGO wrapper is also provided, giving access to functionality not yet implemented natively in Go. The wrapper is implemented in a separate package, meaning that library users who don't need this additional functionality don't need to expose themselves to CGO.

Examples

The following examples show some common operations (errors are omitted for brevity).

WKT

Encoding and decoding WKT:

// Unmarshal from WKT
input := "POLYGON((0 0,0 1,1 1,1 0,0 0))"
g, _ := geom.UnmarshalWKT(input)

// Marshal to WKT
output := g.AsText()
fmt.Println(output) // Prints: POLYGON((0 0,0 1,1 1,1 0,0 0))

WKB

Encoding and decoding WKB directly:

// Marshal as WKB
coords := geom.Coordinates{XY: geom.XY{1.5, 2.5}}
pt := geom.NewPoint(coords)
wkb := pt.AsBinary()
fmt.Println(wkb) // Prints: [1 1 0 0 0 0 0 0 0 0 0 248 63 0 0 0 0 0 0 4 64]

// Unmarshal from WKB
fromWKB, _ := geom.UnmarshalWKB(wkb)
fmt.Println(fromWKB.AsText()) // POINT(1.5 2.5)

Encoding and decoding WKB for integration with PostGIS:

db, _ := sql.Open("postgres", "postgres://...")

db.Exec(`
    CREATE TABLE my_table (
        my_geom geometry(geometry, 4326),
        population double precision
    )`,
)

// Insert our geometry and population data into PostGIS via WKB.
coords := geom.Coordinates{XY: geom.XY{-74.0, 40.7}}
nyc := geom.NewPoint(coords)
db.Exec(`
    INSERT INTO my_table
    (my_geom, population)
    VALUES (ST_GeomFromWKB($1, 4326), $2)`,
    nyc, 8.4e6,
)

// Get the geometry and population data back out of PostGIS via WKB.
var location geom.Geometry
var population float64
db.QueryRow(`
    SELECT ST_AsBinary(my_geom), population
    FROM my_table LIMIT 1`,
).Scan(&location, &population)
fmt.Println(location.AsText(), population) // Prints: POINT(-74 40.7) 8.4e+06

GeoJSON

Encoding and decoding GeoJSON directly:

// Unmarshal geometry from GeoJSON.
raw := `{"type":"Point","coordinates":[-74.0,40.7]}`
var g geom.Geometry
json.NewDecoder(strings.NewReader(raw)).Decode(&g)
fmt.Println(g.AsText()) // Prints: POINT(-74 40.7)

// Marshal back to GeoJSON.
enc := json.NewEncoder(os.Stdout)
enc.Encode(g) // Prints: {"type":"Point","coordinates":[-74,40.7]}

Geometries can also be part of larger structs:

type CityPopulation struct {
    Location   geom.Geometry `json:"loc"`
    Population int           `json:"pop"`
}

// Unmarshal geometry from GeoJSON.
raw := `{"loc":{"type":"Point","coordinates":[-74.0,40.7]},"pop":8400000}`
var v CityPopulation
json.NewDecoder(strings.NewReader(raw)).Decode(&v)
fmt.Println(v.Location.AsText()) // Prints: POINT(-74 40.7)
fmt.Println(v.Population)        // Prints: 8400000

// Marshal back to GeoJSON.
enc := json.NewEncoder(os.Stdout)
enc.Encode(v) // Prints: {"loc":{"type":"Point","coordinates":[-74,40.7]},"pop":8400000}