h3-go

repository·master·Indexed 19 days ago

https://github.com/uber/h3-go

Golang bindings for the H3 Core Library (v4), providing hexagonal hierarchical geospatial indexing. It enables developers to convert coordinates to H3 cells, generate grid disks and rings, fill polygons with cells, and calculate grid distances and paths. The library utilizes CGO and provides core types including Cell, DirectedEdge, and Vertex.

Tokens
4.2K
Snippets
24
Records
29
Agent score
64%

What's inside h3-go

  1. Configure CGO for H3-Go

    master

    H3-Go requires CGO to be enabled (CGO_ENABLED=1) to build. If you encounter errors such as build constraints exclude all Go files..., it means CGO is likely disabled. You can explicitly enable it by setting the CGO_ENABLED environment variable during your build step.

    CGO_ENABLED=1 go build
  2. Core H3 Types: Cell, DirectedEdge, and Vertex

    master

    The h3 package uses three primary types to represent different topological entities in the H3 grid:

    • Cell: An int64 representing a single hexagon (or pentagon) at a specific resolution.
    • DirectedEdge: An int64 representing a directed edge between two adjacent cells.
    • Vertex: An int64 representing a topological vertex shared by three cells.

    All three types implement the Index interface and can be converted to/from strings or hex representations.

  3. Convert LatLng to H3 Cell

    master

    Use h3.NewLatLng to create a latitude/longitude object and h3.LatLngToCell to convert it to an H3 cell at a specific resolution (0-15).

    import "github.com/uber/h3-go/v4"
    import "fmt"
    
    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
    }
  4. Mapping C API to Go API

    master

    The Go API follows Go idiomatic naming conventions. Specifically:

    • The get prefix from the C API has been dropped to follow Go's Getter naming style.
    • Many functions have been added as convenience methods on types (e.g., Cell#Parent instead of just a standalone function).
    • LatLng in Go uses degrees instead of radians.
    C APIGo API
    latLngToCellLatLngToCell, LatLng#Cell
    cellToLatLngCellToLatLng, Cell#LatLng
    cellToBoundaryCellToBoundary, Cell#Boundary
    gridDiskGridDisk, Cell#GridDisk
    gridDisksUnsafeGridDisksUnsafe
    gridDiskDistancesGridDiskDistances, Cell#GridDiskDistances
    gridDiskDistancesSafeGridDiskDistancesSafe, Cell#GridDiskDistancesSafe
    gridDiskDistancesUnsafeGridDiskDistancesUnsafe, Cell#GridDiskDistancesUnsafe
    gridRingGridRing, Cell#GridRing
    gridRingUnsafeGridRingUnsafe, Cell#GridRingUnsafe
    polygonToCellsPolygonToCells, GeoPolygon#Cells
    cellsToMultiPolygonCellsToMultiPolygon
    degsToRadsDegsToRads
    radsToDegsRadsToDegs
    greatCircleDistanceGreatCircleDistance* (3/3)
    getHexagonAreaAvgHexagonAreaAvg* (3/3)
    cellAreaCellArea* (3/3)
    getHexagonEdgeLengthAvgHexagonEdgeLengthAvg* (2/2)
    exactEdgeLengthEdgeLength* (3/3)
    getNumCellsNumCells
    getRes0CellsRes0Cells
    getPentagonsPentagons
    getResolutionResolution
    getBaseCellNumberBaseCellNumber, Cell#BaseCellNumber
    stringToH3IndexFromString, Cell#UnmarshalText
    h3ToStringIndexToString, Cell#String, Cell#MarshalText
    isValidCellCell#IsValid
    cellToParentCell#Parent, Cell#ImmediateParent
    cellToChildrenCell#Children, Cell#ImmediateChildren
    cellToCenterChildCell#CenterChild
    compactCellsCompactCells
    uncompactCellsUncompactCells
    isResClassIIICell#IsResClassIII
    isPentagonCell#IsPentagon
    getIcosahedronFacesCell#IcosahedronFaces
    areNeighborCellsCell#IsNeighbor
    cellsToDirectedEdgeCell#DirectedEdge
    isValidDirectedEdgeDirectedEdge#IsValid
    getDirectedEdgeOriginDirectedEdge#Origin
    getDirectedEdgeDestinationDirectedEdge#Destination
    directedEdgeToCellsDirectedEdge#Cells
    originToDirectedEdgesCell#DirectedEdges
    directedEdgeToBoundaryDirectedEdge#Boundary
    cellToVertexCellToVertex
    cellToVertexesCellToVertexes
    vertexToLatLngVertexToLatLng
    isValidVertexIsValidVertex
    gridDistanceGridDistance, Cell#GridDistance
    gridPathCellsCell#GridPath
    cellToLocalIjCell#LocalIJ
    localIjToCellLocalIJToCell
  5. Get geographic coordinates from a vertex

    master

    Use v.LatLng() or VertexToLatLng(v Vertex) to get the latitude and longitude of a Vertex. Returns a LatLng struct containing Lat and Lng fields.

    latLng, err := vertex.LatLng()
    if err != nil {
        // Handle error
    }
    fmt.Printf("Lat: %f, Lng: %f\n", latLng.Lat, latLng.Lng)
  6. Generate Grid Disks and Rings

    master

    H3 allows you to find cells at specific distances from an origin cell.

    • GridDisk(origin, k): Returns all cells within grid distance k of the origin (the k-ring).
    • GridRing(origin, k): Returns only the cells at exactly grid distance k (the 'hollow' ring).
    • GridDiskDistances(origin, k): Returns cells grouped by their distance from the origin, where the outer slice index corresponds to the distance.

    Note on Unsafe methods: Functions suffixed with Unsafe (e.g., GridDiskUnsafe) are faster but have undefined behavior if the operation crosses a pentagon or enters a pentagon distortion area.

    // Get all cells in the 2-ring
    disk, err := cell.GridDisk(2)
    
    // Get cells at exactly distance 2
    ring, err := cell.GridRing(2)
    
    // Get cells grouped by distance
    dists, err := cell.GridDiskDistances(2)
    // dists[0] contains origin, dists[1] contains neighbors, etc.
  7. Convert Cells to MultiPolygon

    master

    To visualize a set of H3 cells as a geographic shape, use CellsToMultiPolygon. This returns a slice of GeoPolygon objects describing the outlines of the hexagons. It is expected that all input cells have the same resolution and no duplicates.

    polygons, err := h3.CellsToMultiPolygon(cells)
  8. Validate an H3 index

    master

    The generic function IsValidIndex[T Index](index T) checks if a given H3 index (of type Cell, DirectedEdge, or Vertex) is valid.

    • For Cell, validation is performed via pure Go bit manipulation.
    • For DirectedEdge and Vertex, validation calls through to CGo as it requires coordinate geometry.
    if IsValidIndex(myCell) {
        // cell is valid
    }
  9. Calculate the total number of cells at a resolution

    master

    Use the NumCells(res int) function to get the total number of H3 cells existing at a specific resolution. If the provided resolution is outside the valid range [0, maxResolution], the function returns 0.

    count := h3go.NumCells(5)
  10. Convert LatLng to Cell

    master

    To find the H3 Cell that contains a specific geographic coordinate, use LatLngToCell or the Cell method on a LatLng struct. You must specify the desired resolution (0-15).

    // Using the helper function
    cell, err := h3.LatLngToCell(h3.NewLatLng(37.7749, -122.4194), 9)
    
    // Or using the method on LatLng
    latLng := h3.LatLng{Lat: 37.7749, Lng: -122.4194}
    cell, err := latLng.Cell(9)