geojson

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2021 License: MIT Imports: 4 Imported by: 0

README

go.geojson

Go.geojson is a package for encoding and decoding GeoJSON into Go structs. Supports both the json.Marshaler and json.Unmarshaler interfaces as well as sql.Scanner for directly scanning PostGIS query results. The package also provides helper functions such as UnmarshalFeatureCollection, UnmarshalFeature and UnmarshalGeometry.

Important

This package is best for lightweight interaction with GeoJSON. If you want to actually do stuff with the geometry take a look at orb/geojson which decodes the geometries into orb types which you can do all sorts of things with.

To install
go get github.com/paulmach/go.geojson
To use, imports as package name geojson:
import "github.com/paulmach/go.geojson"

Build Status Godoc Reference

Examples

  • Unmarshalling (JSON -> Go)

    go.geojson supports both the json.Marshaler and json.Unmarshaler interfaces as well as helper functions such as UnmarshalFeatureCollection, UnmarshalFeature and UnmarshalGeometry.

      // Feature Collection
      rawFeatureJSON := []byte(`
        { "type": "FeatureCollection",
          "features": [
            { "type": "Feature",
              "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
              "properties": {"prop0": "value0"}
            }
          ]
        }`)
    
      fc1, err := geojson.UnmarshalFeatureCollection(rawFeatureJSON)
    
      fc2 := geojson.NewFeatureCollection()
      err := json.Unmarshal(rawJSON, fc2)
    
      // Geometry
      rawGeometryJSON := []byte(`{"type": "Point", "coordinates": [102.0, 0.5]}`)
      g, err := geojson.UnmarshalGeometry(rawGeometryJSON)
    
      g.IsPoint() == true
      g.Point == []float64{102.0, 0.5}
    
  • Marshalling (Go -> JSON)
      g := geojson.NewPointGeometry([]float64{1, 2})
      rawJSON, err := g.MarshalJSON()
    
      fc := geojson.NewFeatureCollection()
      fc.AddFeature(geojson.NewPointFeature([]float64{1,2}))
      rawJSON, err := fc.MarshalJSON()
    
  • Scanning PostGIS query results
      row := db.QueryRow("SELECT ST_AsGeoJSON(the_geom) FROM postgis_table)
    
      var geometry *geojson.Geometry
      row.Scan(&geometry)
    
  • Dealing with different Geometry types

    A geometry can be of several types, causing problems in a statically typed language. Thus there is a separate attribute on Geometry for each type. See the Geometry object for more details.

      g := geojson.UnmarshalGeometry([]byte(`
      	{
            "type": "LineString",
            "coordinates": [
              [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
            ]
          }`))
    
      switch {
      case g.IsPoint():
      	// do something with g.Point
      case g.IsLineString():
      	// do something with g.LineString
      }
    

Feature Properties

GeoJSON Features can have properties of any type. This can cause issues in a statically typed language such as Go. So, included are some helper methods on the Feature object to ease the pain.

// functions to do the casting for you
func (f Feature) PropertyBool(key string) (bool, error) {
func (f Feature) PropertyInt(key string) (int, error) {
func (f Feature) PropertyFloat64(key string) (float64, error) {
func (f Feature) PropertyString(key string) (string, error) {

// functions that hide the error and let you define default
func (f Feature) PropertyMustBool(key string, def ...bool) bool {
func (f Feature) PropertyMustInt(key string, def ...int) int {
func (f Feature) PropertyMustFloat64(key string, def ...float64) float64 {
func (f Feature) PropertyMustString(key string, def ...string) string {

Documentation

Overview

Package geojson is a library for encoding and decoding GeoJSON into Go structs. Supports both the json.Marshaler and json.Unmarshaler interfaces as well as helper functions such as `UnmarshalFeatureCollection`, `UnmarshalFeature` and `UnmarshalGeometry`.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Feature

type Feature struct {
	ID          interface{}            `json:"id,omitempty"`
	Type        string                 `json:"type"`
	BoundingBox []float64              `json:"bbox,omitempty"`
	Geometry    *Geometry              `json:"geometry"`
	Properties  map[string]interface{} `json:"properties"`
	CRS         map[string]interface{} `json:"crs,omitempty"` // Coordinate Reference System Objects are not currently supported
}

A Feature corresponds to GeoJSON feature object

func NewCollectionFeature

func NewCollectionFeature(geometries ...*Geometry) *Feature

NewCollectionFeature creates and initializes a GeoJSON feature with a geometry collection geometry using the given geometries.

func NewFeature

func NewFeature(geometry *Geometry) *Feature

NewFeature creates and initializes a GeoJSON feature given the required attributes.

func NewLineStringFeature

func NewLineStringFeature(coordinates [][]float64) *Feature

NewLineStringFeature creates and initializes a GeoJSON feature with a line string geometry using the given coordinates.

func NewMultiLineStringFeature

func NewMultiLineStringFeature(lines ...[][]float64) *Feature

NewMultiLineStringFeature creates and initializes a GeoJSON feature with a multi-line string geometry using the given lines.

func NewMultiPointFeature

func NewMultiPointFeature(coordinates ...[]float64) *Feature

NewMultiPointFeature creates and initializes a GeoJSON feature with a multi-point geometry using the given coordinates.

func NewMultiPolygonFeature

func NewMultiPolygonFeature(polygons ...[][][]float64) *Feature

NewMultiPolygonFeature creates and initializes a GeoJSON feature with a multi-polygon geometry using the given polygons.

func NewPointFeature

func NewPointFeature(coordinate []float64) *Feature

NewPointFeature creates and initializes a GeoJSON feature with a point geometry using the given coordinate.

func NewPolygonFeature

func NewPolygonFeature(polygon [][][]float64) *Feature

NewPolygonFeature creates and initializes a GeoJSON feature with a polygon geometry using the given polygon.

func UnmarshalFeature

func UnmarshalFeature(data []byte) (*Feature, error)

UnmarshalFeature decodes the data into a GeoJSON feature. Alternately one can call json.Unmarshal(f) directly for the same result.

func (Feature) MarshalJSON

func (f Feature) MarshalJSON() ([]byte, error)

MarshalJSON converts the feature object into the proper JSON. It will handle the encoding of all the child geometries. Alternately one can call json.Marshal(f) directly for the same result.

func (*Feature) PropertyBool

func (f *Feature) PropertyBool(key string) (bool, error)

PropertyBool type asserts a property to `bool`.

func (*Feature) PropertyFloat64

func (f *Feature) PropertyFloat64(key string) (float64, error)

PropertyFloat64 type asserts a property to `float64`.

func (*Feature) PropertyInt

func (f *Feature) PropertyInt(key string) (int, error)

PropertyInt type asserts a property to `int`.

func (*Feature) PropertyMustBool

func (f *Feature) PropertyMustBool(key string, def ...bool) bool

PropertyMustBool guarantees the return of a `bool` (with optional default)

useful when you explicitly want a `bool` in a single value return context:

myFunc(f.PropertyMustBool("param1"), f.PropertyMustBool("optional_param", true))

func (*Feature) PropertyMustFloat64

func (f *Feature) PropertyMustFloat64(key string, def ...float64) float64

PropertyMustFloat64 guarantees the return of a `float64` (with optional default)

useful when you explicitly want a `float64` in a single value return context:

myFunc(f.PropertyMustFloat64("param1"), f.PropertyMustFloat64("optional_param", 10.1))

func (*Feature) PropertyMustInt

func (f *Feature) PropertyMustInt(key string, def ...int) int

PropertyMustInt guarantees the return of a `int` (with optional default)

useful when you explicitly want a `int` in a single value return context:

myFunc(f.PropertyMustInt("param1"), f.PropertyMustInt("optional_param", 123))

func (*Feature) PropertyMustString

func (f *Feature) PropertyMustString(key string, def ...string) string

PropertyMustString guarantees the return of a `string` (with optional default)

useful when you explicitly want a `string` in a single value return context:

myFunc(f.PropertyMustString("param1"), f.PropertyMustString("optional_param", "default"))

func (*Feature) PropertyString

func (f *Feature) PropertyString(key string) (string, error)

PropertyString type asserts a property to `string`.

func (*Feature) SetProperty

func (f *Feature) SetProperty(key string, value interface{})

SetProperty provides the inverse of all the property functions and is here for consistency.

type FeatureCollection

type FeatureCollection struct {
	Type        string                 `json:"type"`
	BoundingBox []float64              `json:"bbox,omitempty"`
	Features    []*Feature             `json:"features"`
	CRS         map[string]interface{} `json:"crs,omitempty"` // Coordinate Reference System Objects are not currently supported
}

A FeatureCollection correlates to a GeoJSON feature collection.

func NewFeatureCollection

func NewFeatureCollection() *FeatureCollection

NewFeatureCollection creates and initializes a new feature collection.

func UnmarshalFeatureCollection

func UnmarshalFeatureCollection(data []byte) (*FeatureCollection, error)

UnmarshalFeatureCollection decodes the data into a GeoJSON feature collection. Alternately one can call json.Unmarshal(fc) directly for the same result.

Example
package main

import (
	"fmt"

	geojson "github.com/paulmach/go.geojson"
)

func main() {
	rawFeatureJSON := []byte(`
		  { "type": "FeatureCollection",
		    "features": [
		      { "type": "Feature",
		        "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
		        "properties": {"prop0": "value0"}
		      }
		    ]
		  }`)

	fc, err := geojson.UnmarshalFeatureCollection(rawFeatureJSON)
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}

	fmt.Printf("%s", fc.Features[0].Properties["prop0"])
}
Output:

value0

func (*FeatureCollection) AddFeature

func (fc *FeatureCollection) AddFeature(feature *Feature) *FeatureCollection

AddFeature appends a feature to the collection.

func (FeatureCollection) MarshalJSON

func (fc FeatureCollection) MarshalJSON() ([]byte, error)

MarshalJSON converts the feature collection object into the proper JSON. It will handle the encoding of all the child features and geometries. Alternately one can call json.Marshal(fc) directly for the same result.

Example
package main

import (
	"fmt"

	geojson "github.com/paulmach/go.geojson"
)

func main() {
	fc := geojson.NewFeatureCollection()
	fc.AddFeature(geojson.NewPointFeature([]float64{1, 2}))
	rawJSON, err := fc.MarshalJSON()
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}

	fmt.Printf("%s", string(rawJSON))
}
Output:

{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[1,2]},"properties":null}]}

type Geometry

type Geometry struct {
	Type            GeometryType `json:"type"`
	BoundingBox     []float64    `json:"bbox,omitempty"`
	Point           []float64
	MultiPoint      [][]float64
	LineString      [][]float64
	MultiLineString [][][]float64
	Polygon         [][][]float64
	MultiPolygon    [][][][]float64
	Geometries      []*Geometry
	CRS             map[string]interface{} `json:"crs,omitempty"` // Coordinate Reference System Objects are not currently supported
}

A Geometry correlates to a GeoJSON geometry object.

func NewCollectionGeometry

func NewCollectionGeometry(geometries ...*Geometry) *Geometry

NewCollectionGeometry creates and initializes a geometry collection geometry with the given geometries.

func NewLineStringGeometry

func NewLineStringGeometry(coordinates [][]float64) *Geometry

NewLineStringGeometry creates and initializes a line string geometry with the given coordinates.

func NewMultiLineStringGeometry

func NewMultiLineStringGeometry(lines ...[][]float64) *Geometry

NewMultiLineStringGeometry creates and initializes a multi-line string geometry with the given lines.

func NewMultiPointGeometry

func NewMultiPointGeometry(coordinates ...[]float64) *Geometry

NewMultiPointGeometry creates and initializes a multi-point geometry with the given coordinates.

func NewMultiPolygonGeometry

func NewMultiPolygonGeometry(polygons ...[][][]float64) *Geometry

NewMultiPolygonGeometry creates and initializes a multi-polygon geometry with the given polygons.

func NewPointGeometry

func NewPointGeometry(coordinate []float64) *Geometry

NewPointGeometry creates and initializes a point geometry with the give coordinate.

func NewPolygonGeometry

func NewPolygonGeometry(polygon [][][]float64) *Geometry

NewPolygonGeometry creates and initializes a polygon geometry with the given polygon.

func UnmarshalGeometry

func UnmarshalGeometry(data []byte) (*Geometry, error)

UnmarshalGeometry decodes the data into a GeoJSON geometry. Alternately one can call json.Unmarshal(g) directly for the same result.

Example
package main

import (
	"fmt"

	geojson "github.com/paulmach/go.geojson"
)

func main() {
	rawGeometryJSON := []byte(`{"type": "Point", "coordinates": [102.0, 0.5]}`)
	g, err := geojson.UnmarshalGeometry(rawGeometryJSON)
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}

	fmt.Printf("%s", g.Type)
}
Output:

Point

func (*Geometry) IsCollection

func (g *Geometry) IsCollection() bool

IsCollection returns true with the geometry object is a GeometryCollection type.

func (*Geometry) IsLineString

func (g *Geometry) IsLineString() bool

IsLineString returns true with the geometry object is a LineString type.

func (*Geometry) IsMultiLineString

func (g *Geometry) IsMultiLineString() bool

IsMultiLineString returns true with the geometry object is a LineString type.

func (*Geometry) IsMultiPoint

func (g *Geometry) IsMultiPoint() bool

IsMultiPoint returns true with the geometry object is a MultiPoint type.

func (*Geometry) IsMultiPolygon

func (g *Geometry) IsMultiPolygon() bool

IsMultiPolygon returns true with the geometry object is a MultiPolygon type.

func (*Geometry) IsPoint

func (g *Geometry) IsPoint() bool

IsPoint returns true with the geometry object is a Point type.

func (*Geometry) IsPolygon

func (g *Geometry) IsPolygon() bool

IsPolygon returns true with the geometry object is a Polygon type.

func (Geometry) MarshalJSON

func (g Geometry) MarshalJSON() ([]byte, error)

MarshalJSON converts the geometry object into the correct JSON. This fulfills the json.Marshaler interface.

func (*Geometry) Scan

func (g *Geometry) Scan(value interface{}) error

Scan implements the sql.Scanner interface allowing geometry structs to be passed into rows.Scan(...interface{}) The columns must be received as GeoJSON Geometry. When using PostGIS a spatial column would need to be wrapped in ST_AsGeoJSON.

func (*Geometry) UnmarshalJSON

func (g *Geometry) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the data into a GeoJSON geometry. This fulfills the json.Unmarshaler interface.

func (*Geometry) Value added in v1.4.1

func (g *Geometry) Value() (driver.Value, error)

Value implements the driver Valuer interface. The columns must be sending as GeoJSON Geometry. When using PostGIS a spatial column would need to be wrapped in ST_GeomFromGeoJSON.

type GeometryType

type GeometryType string

A GeometryType serves to enumerate the different GeoJSON geometry types.

const (
	GeometryPoint           GeometryType = "Point"
	GeometryMultiPoint      GeometryType = "MultiPoint"
	GeometryLineString      GeometryType = "LineString"
	GeometryMultiLineString GeometryType = "MultiLineString"
	GeometryPolygon         GeometryType = "Polygon"
	GeometryMultiPolygon    GeometryType = "MultiPolygon"
	GeometryCollection      GeometryType = "GeometryCollection"
)

The geometry types supported by GeoJSON 1.0

Jump to

Keyboard shortcuts

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