h3

package module
v4.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2024 License: Apache-2.0 Imports: 7 Imported by: 19

README

H3 Logo

Build Coverage Status Go Report Card License GoDoc H3 Version

H3-Go is looking for a maintainer familiar with Go, C, and H3. Volunteers welcome! Please get in touch with us on the H3 Slack.

H3-Go

This library provides Golang bindings for the H3 Core Library. For API reference, see the H3 Documentation.

This is v4 of this library, supporting H3 v4.

Check out v3 or checkout the git tag for the version you need.

Migrating from v3?

Check out v3 to v4 migration guide. There have been no breaking changes to the format of H3 indexes. Indexes generated by older versions can be parsed in v4, and vice-versa.

Usage

Prerequisites

H3-Go requires CGO (CGO_ENABLED=1) in order to be built. Go should do the right thing when including this library:

The cgo tool is enabled by default for native builds on systems where it is expected to work. It is disabled by default when cross-compiling. You can control this by setting the CGO_ENABLED environment variable when running the go tool: set it to 1 to enable the use of cgo, and to 0 to disable it. The go tool will set the build constraint "cgo" if cgo is enabled. The special import "C" implies the "cgo" build constraint, as though the file also said "// +build cgo". Therefore, if cgo is disabled, files that import "C" will not be built by the go tool. (For more about build constraints see https://golang.org/pkg/go/build/#hdr-Build_Constraints).

If you see errors/warnings like "build constraints exclude all Go files...", then the cgo build constraint is likely disabled; try setting CGO_ENABLED=1 environment variable in your go build step.

Installation

go get github.com/uber/h3-go/v4

Quickstart

import "github.com/uber/h3-go/v4"

func ExampleLatLngToCell() {
 latLng := h3.NewLatLng(37.775938728915946, -122.41795063018799)
 resolution := 9 // between 0 (biggest cell) and 15 (smallest cell)

 cell := h3.LatLngToCell(latLng, resolution)

 fmt.Printf("%s", cell)
 // Output:
 // 8928308280fffff
}

C API

Notes

  • LatLng returns Lat and Lng as degrees, instead of radians.
  • H3 C API function prefixes of get have been dropped in support of Golang's Getter naming style.
  • Convenience methods have been added to various types where that type was the main or only argument.

Bindings

C API Go API
latLngToCell LatLngToCell, LatLng#Cell
cellToLatLng CellToLatLng, Cell#LatLng
cellToBoundary CellToBoundary, Cell#Boundary
gridDisk GridDisk, Cell#GridDisk
gridDiskDistances GridDiskDistances, Cell#GridDiskDistances
gridRingUnsafe N/A
polygonToCells PolygonToCells, GeoPolygon#Cells
cellsToMultiPolygon CellsToMultiPolygon
degsToRads DegsToRads
radsToDegs RadsToDegs
greatCircleDistance GreatCircleDistance* (3/3)
getHexagonAreaAvg HexagonAreaAvg* (3/3)
cellArea CellArea* (3/3)
getHexagonEdgeLengthAvg HexagonEdgeLengthAvg* (2/2)
exactEdgeLength EdgeLength* (3/3)
getNumCells NumCells
getRes0Cells Res0Cells
getPentagons Pentagons
getResolution Resolution
getBaseCellNumber BaseCellNumber, Cell#BaseCellNumber
stringToH3 IndexFromString, Cell#UnmarshalText
h3ToString IndexToString, Cell#String, Cell#MarshalText
isValidCell Cell#IsValid
cellToParent Cell#Parent, Cell#ImmediateParent
cellToChildren Cell#Children Cell#ImmediateChildren
cellToCenterChild Cell#CenterChild
compactCells CompactCells
uncompactCells UncompactCells
isResClassIII Cell#IsResClassIII
isPentagon Cell#IsPentagon
getIcosahedronFaces Cell#IcosahedronFaces
areNeighborCells Cell#IsNeighbor
cellsToDirectedEdge Cell#DirectedEdge
isValidDirectedEdge DirectedEdge#IsValid
getDirectedEdgeOrigin DirectedEdge#Origin
getDirectedEdgeDestination DirectedEdge#Destination
directedEdgeToCells DirectedEdge#Cells
originToDirectedEdges Cell#DirectedEdges
directedEdgeToBoundary DirectedEdge#Boundary
cellToVertex CellToVertex
cellToVertexes CellToVertexes
vertexToLatLng VertexToLatLng
isValidVertex IsValidVertex
gridDistance GridDistance, Cell#GridDistance
gridPathCells GridPath, Cell#GridPath
cellToLocalIj CellToLocalIJ
localIjToCell LocalIJToCell

CGO

The H3 C source code and header files are copied into this project to optimize for portability. h3-go can be imported into any Go project for any platform that CGO supports.

Contributing

Pull requests and Github issues are welcome. Please read our contributing guide for more information.

H3-Go is licensed under the Apache 2.0 License.

Documentation

Overview

Package h3 is the go binding for Uber's H3 Geo Index system. It uses cgo to link with a statically compiled h3 library

Index

Examples

Constants

View Source
const (
	// MaxCellBndryVerts is the maximum number of vertices that can be used
	// to represent the shape of a cell.
	MaxCellBndryVerts = C.MAX_CELL_BNDRY_VERTS

	// MaxResolution is the maximum H3 resolution a LatLng can be indexed to.
	MaxResolution = C.MAX_H3_RES

	// The number of faces on an icosahedron
	NumIcosaFaces = C.NUM_ICOSA_FACES

	// The number of H3 base cells
	NumBaseCells = C.NUM_BASE_CELLS

	// The number of H3 pentagon cells (same at every resolution)
	NumPentagons = C.NUM_PENTAGONS

	// InvalidH3Index is a sentinel value for an invalid H3 index.
	InvalidH3Index = C.H3_NULL

	DegsToRads = math.Pi / 180.0
	RadsToDegs = 180.0 / math.Pi
)

Variables

View Source
var (
	ErrFailed                = errors.New("the operation failed")
	ErrDomain                = errors.New("argument was outside of acceptable range")
	ErrLatLngDomain          = errors.New("latitude or longitude arguments were outside of acceptable range")
	ErrResolutionDomain      = errors.New("resolution argument was outside of acceptable range")
	ErrCellInvalid           = errors.New("H3Index cell argument was not valid")
	ErrDirectedEdgeInvalid   = errors.New("H3Index directed edge argument was not valid")
	ErrUndirectedEdgeInvalid = errors.New("H3Index undirected edge argument was not valid")
	ErrVertexInvalid         = errors.New("H3Index vertex argument was not valid")
	ErrPentagon              = errors.New("pentagon distortion was encountered")
	ErrDuplicateInput        = errors.New("duplicate input was encountered in the arguments")
	ErrNotNeighbors          = errors.New("H3Index cell arguments were not neighbors")
	ErrRsolutionMismatch     = errors.New("H3Index cell arguments had incompatible resolutions")
	ErrMemoryAlloc           = errors.New("necessary memory allocation failed")
	ErrMemoryBounds          = errors.New("bounds of provided memory were not large enough")
	ErrOptionInvalid         = errors.New("mode or flags argument was not valid")

	ErrUnknown = errors.New("unknown error code returned by H3")
)

Error codes.

Functions

func BaseCellNumber

func BaseCellNumber(h Cell) int

BaseCellNumber returns the integer ID (0-121) of the base cell the H3Index h belongs to.

func CellAreaKm2

func CellAreaKm2(c Cell) (float64, error)

CellAreaKm2 returns the exact area of specific cell in square kilometers.

func CellAreaM2

func CellAreaM2(c Cell) (float64, error)

CellAreaM2 returns the exact area of specific cell in square meters.

func CellAreaRads2

func CellAreaRads2(c Cell) (float64, error)

CellAreaRads2 returns the exact area of specific cell in square radians.

func CellToChildPos added in v4.1.0

func CellToChildPos(a Cell, resolution int) (int, error)

CellToChildPos returns the position of the cell a within an ordered list of all children of the cell's parent at the specified resolution.

func EdgeLengthKm

func EdgeLengthKm(e DirectedEdge) (float64, error)

EdgeLengthKm returns the exact edge length of specific unidirectional edge in kilometers.

func EdgeLengthM

func EdgeLengthM(e DirectedEdge) (float64, error)

EdgeLengthM returns the exact edge length of specific unidirectional edge in meters.

func EdgeLengthRads

func EdgeLengthRads(e DirectedEdge) (float64, error)

EdgeLengthRads returns the exact edge length of specific unidirectional edge in radians.

func GreatCircleDistanceKm

func GreatCircleDistanceKm(a, b LatLng) float64

PointDistKm returns the "great circle" or "haversine" distance between pairs of LatLng points (lat/lng pairs) in kilometers.

func GreatCircleDistanceM

func GreatCircleDistanceM(a, b LatLng) float64

PointDistM returns the "great circle" or "haversine" distance between pairs of LatLng points (lat/lng pairs) in meters.

func GreatCircleDistanceRads

func GreatCircleDistanceRads(a, b LatLng) float64

PointDistRads returns the "great circle" or "haversine" distance between pairs of LatLng points (lat/lng pairs) in radians.

func GridDiskDistances

func GridDiskDistances(origin Cell, k int) ([][]Cell, error)

GridDiskDistances produces cells within grid distance k of the origin cell.

k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and all neighboring cells, and so on.

Outer slice is ordered from origin outwards. Inner slices are in no particular order. Elements of the output array may be left zero, as can happen when crossing a pentagon.

func GridDistance

func GridDistance(a, b Cell) (int, error)

func HexagonAreaAvgKm2

func HexagonAreaAvgKm2(resolution int) (float64, error)

HexAreaKm2 returns the average hexagon area in square kilometers at the given resolution.

func HexagonAreaAvgM2

func HexagonAreaAvgM2(resolution int) (float64, error)

HexAreaM2 returns the average hexagon area in square meters at the given resolution.

func HexagonEdgeLengthAvgKm

func HexagonEdgeLengthAvgKm(resolution int) (float64, error)

HexagonEdgeLengthAvgKm returns the average hexagon edge length in kilometers at the given resolution.

func HexagonEdgeLengthAvgM

func HexagonEdgeLengthAvgM(resolution int) (float64, error)

HexagonEdgeLengthAvgM returns the average hexagon edge length in meters at the given resolution.

func IndexFromString

func IndexFromString(s string) uint64

IndexFromString returns a Cell from a string. Should call c.IsValid() to check if the Cell is valid before using it.

func IndexToString

func IndexToString(i uint64) string

IndexToString returns a Cell from a string. Should call c.IsValid() to check if the Cell is valid before using it.

func IsValidVertex added in v4.1.2

func IsValidVertex(c Cell) bool

func NumCells

func NumCells(resolution int) int

NumCells returns the number of cells at the given resolution.

Types

type Cell

type Cell int64

Cell is an Index that identifies a single hexagon cell at a resolution.

func CellToVertex added in v4.1.2

func CellToVertex(c Cell, vertexNum int) (Cell, error)

func CellToVertexes added in v4.1.2

func CellToVertexes(c Cell) ([]Cell, error)

func ChildPosToCell added in v4.1.0

func ChildPosToCell(position int, a Cell, resolution int) (Cell, error)

ChildPosToCell returns the child of cell a at a given position within an ordered list of all children at the specified resolution.

func CompactCells

func CompactCells(in []Cell) ([]Cell, error)

CompactCells merges full sets of children into their parent H3Index recursively, until no more merges are possible.

func GridDisk

func GridDisk(origin Cell, k int) ([]Cell, error)

GridDisk produces cells within grid distance k of the origin cell.

k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and all neighboring cells, and so on.

Output is placed in an array in no particular order. Elements of the output array may be left zero, as can happen when crossing a pentagon.

func GridPath

func GridPath(a, b Cell) ([]Cell, error)

func LatLngToCell

func LatLngToCell(latLng LatLng, resolution int) (Cell, error)

LatLngToCell returns the Cell at resolution for a geographic coordinate.

Example
latLng := h3.NewLatLng(37.775938728915946, -122.41795063018799)
resolution := 9

c, err := h3.LatLngToCell(latLng, resolution)
if err != nil {
	panic(err)
}

fmt.Printf("%s", c)
Output:

8928308280fffff

func LocalIJToCell

func LocalIJToCell(origin Cell, ij CoordIJ) (Cell, error)

func Pentagons

func Pentagons(resolution int) ([]Cell, error)

Pentagons returns all the pentagons at resolution.

func PolygonToCells

func PolygonToCells(polygon GeoPolygon, resolution int) ([]Cell, error)

PolygonToCells takes a given GeoJSON-like data structure fills it with the hexagon cells that are contained by the GeoJSON-like data structure.

This implementation traces the GeoJSON geoloop(s) in cartesian space with hexagons, tests them and their neighbors to be contained by the geoloop(s), and then any newly found hexagons are used to test again until no new hexagons are found.

func Res0Cells

func Res0Cells() ([]Cell, error)

Res0Cells returns all the cells at resolution 0.

func UncompactCells

func UncompactCells(in []Cell, resolution int) ([]Cell, error)

UncompactCells splits every H3Index in in if its resolution is greater than resolution recursively. Returns all the H3Indexes at resolution resolution.

func (Cell) BaseCellNumber

func (c Cell) BaseCellNumber() int

BaseCellNumber returns the integer ID (0-121) of the base cell the H3Index h belongs to.

func (Cell) Boundary

func (c Cell) Boundary() (CellBoundary, error)

Boundary returns a CellBoundary of the Cell.

func (Cell) CenterChild

func (c Cell) CenterChild(resolution int) (Cell, error)

CenterChild returns the center child Cell of this Cell.

func (Cell) ChildPos added in v4.1.0

func (c Cell) ChildPos(resolution int) (int, error)

ChildPos returns the position of the cell within an ordered list of all children of the cell's parent at the specified resolution.

func (Cell) ChildPosToCell added in v4.1.0

func (c Cell) ChildPosToCell(position int, resolution int) (Cell, error)

ChildPosToCell returns the child cell at a given position within an ordered list of all children at the specified resolution.

func (Cell) Children

func (c Cell) Children(resolution int) ([]Cell, error)

Children returns the children or grandchildren cells of this Cell.

func (Cell) DirectedEdge

func (c Cell) DirectedEdge(other Cell) (DirectedEdge, error)

DirectedEdge returns a DirectedEdge from this Cell to other.

func (Cell) DirectedEdges

func (c Cell) DirectedEdges() ([]DirectedEdge, error)

DirectedEdges returns 6 directed edges with h as the origin.

func (Cell) GridDisk

func (c Cell) GridDisk(k int) ([]Cell, error)

GridDisk produces cells within grid distance k of the origin cell.

k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and all neighboring cells, and so on.

Output is placed in an array in no particular order. Elements of the output array may be left zero, as can happen when crossing a pentagon.

func (Cell) GridDiskDistances

func (c Cell) GridDiskDistances(k int) ([][]Cell, error)

GridDiskDistances produces cells within grid distance k of the origin cell.

k-ring 0 is defined as the origin cell, k-ring 1 is defined as k-ring 0 and all neighboring cells, and so on.

Outer slice is ordered from origin outwards. Inner slices are in no particular order. Elements of the output array may be left zero, as can happen when crossing a pentagon.

func (Cell) GridDistance

func (c Cell) GridDistance(other Cell) (int, error)

func (Cell) GridPath

func (c Cell) GridPath(other Cell) ([]Cell, error)

func (Cell) IcosahedronFaces

func (c Cell) IcosahedronFaces() ([]int, error)

IcosahedronFaces finds all icosahedron faces (0-19) intersected by this Cell.

func (Cell) ImmediateChildren

func (c Cell) ImmediateChildren() ([]Cell, error)

ImmediateChildren returns the children or grandchildren cells of this Cell.

func (Cell) ImmediateParent

func (c Cell) ImmediateParent() (Cell, error)

Parent returns the parent or grandparent Cell of this Cell.

func (Cell) IsNeighbor

func (c Cell) IsNeighbor(other Cell) (bool, error)

IsNeighbor returns true if this Cell is a neighbor of the other Cell.

func (Cell) IsPentagon

func (c Cell) IsPentagon() bool

IsPentagon returns true if this is a pentagon.

func (Cell) IsResClassIII

func (c Cell) IsResClassIII() bool

IsResClassIII returns true if this is a class III index. If false, this is a class II index.

func (Cell) IsValid

func (c Cell) IsValid() bool

IsValid returns if a Cell is a valid cell (hexagon or pentagon).

func (Cell) LatLng

func (c Cell) LatLng() (LatLng, error)

LatLng returns the Cell at resolution for a geographic coordinate.

func (Cell) MarshalText

func (c Cell) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (Cell) Parent

func (c Cell) Parent(resolution int) (Cell, error)

Parent returns the parent or grandparent Cell of this Cell.

func (Cell) Resolution

func (c Cell) Resolution() int

func (Cell) String

func (c Cell) String() string

String returns the string representation of the H3Index h.

func (*Cell) UnmarshalText

func (c *Cell) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type CellBoundary

type CellBoundary []LatLng

CellBoundary is a slice of LatLng. Note, len(CellBoundary) will never exceed MaxCellBndryVerts.

func CellToBoundary

func CellToBoundary(c Cell) (CellBoundary, error)

CellToBoundary returns a CellBoundary of the Cell.

type CoordIJ

type CoordIJ struct {
	I, J int
}

func CellToLocalIJ

func CellToLocalIJ(origin, cell Cell) (CoordIJ, error)

type DirectedEdge

type DirectedEdge int64

DirectedEdge is an Index that identifies a directed edge between two cells.

func (DirectedEdge) Boundary

func (e DirectedEdge) Boundary() (CellBoundary, error)

Boundary provides the coordinates of the boundary of the directed edge. Note, the type returned is CellBoundary, but the coordinates will be from the center of the origin to the center of the destination. There may be more than 2 coordinates to account for crossing faces.

func (DirectedEdge) Cells

func (e DirectedEdge) Cells() ([]Cell, error)

Cells returns the origin and destination cells in that order.

func (DirectedEdge) Destination

func (e DirectedEdge) Destination() (Cell, error)

Destination returns the destination cell of this directed edge.

func (DirectedEdge) IsValid

func (e DirectedEdge) IsValid() bool

func (DirectedEdge) Origin

func (e DirectedEdge) Origin() (Cell, error)

Origin returns the origin cell of this directed edge.

func (DirectedEdge) Resolution

func (e DirectedEdge) Resolution() int

type GeoLoop

type GeoLoop []LatLng

GeoLoop is a slice of LatLng points that make up a loop.

type GeoPolygon

type GeoPolygon struct {
	GeoLoop GeoLoop
	Holes   []GeoLoop
}

GeoPolygon is a GeoLoop with 0 or more GeoLoop holes.

func CellsToMultiPolygon

func CellsToMultiPolygon(cells []Cell) ([]GeoPolygon, error)

CellsToMultiPolygon takes a set of cells and creates GeoPolygon(s) describing the outline(s) of a set of hexagons. Polygon outlines will follow GeoJSON MultiPolygon order: Each polygon will have one outer loop, which is first in the list, followed by any holes.

It is expected that all hexagons in the set have the same resolution and that the set contains no duplicates. Behavior is undefined if duplicates or multiple resolutions are present, and the algorithm may produce unexpected or invalid output.

func (GeoPolygon) Cells

func (p GeoPolygon) Cells(resolution int) ([]Cell, error)

PolygonToCells takes a given GeoJSON-like data structure fills it with the hexagon cells that are contained by the GeoJSON-like data structure.

This implementation traces the GeoJSON geoloop(s) in cartesian space with hexagons, tests them and their neighbors to be contained by the geoloop(s), and then any newly found hexagons are used to test again until no new hexagons are found.

type LatLng

type LatLng struct {
	Lat, Lng float64
}

LatLng is a struct for geographic coordinates in degrees.

func CellToLatLng

func CellToLatLng(c Cell) (LatLng, error)

CellToLatLng returns the geographic centerpoint of a Cell.

func NewLatLng

func NewLatLng(lat, lng float64) LatLng

func VertexToLatLng added in v4.1.2

func VertexToLatLng(vertex Cell) (LatLng, error)

func (LatLng) Cell

func (g LatLng) Cell(resolution int) (Cell, error)

Cell returns the Cell at resolution for a geographic coordinate.

func (LatLng) String

func (g LatLng) String() string

Jump to

Keyboard shortcuts

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