### Install H3-Go Library Source: https://github.com/uber/h3-go/blob/master/README.md Use 'go get' to install the v4 of the H3-Go library. ```bash go get github.com/uber/h3-go/v4 ``` -------------------------------- ### Install Dependencies Source: https://github.com/uber/h3-go/blob/master/CONTRIBUTING.md Installs all necessary development dependencies for the project. ```bash go get -t ./... ``` -------------------------------- ### Get Cell Boundary Vertices Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md This example demonstrates how to retrieve all vertices that form the boundary of a given H3 cell. It iterates through the vertices, checks their validity, and prints their geographic coordinates. ```go package main import ( "fmt" "github.com/uber/h3-go/v4" ) func main() { cell := h3.CellFromString("8928308280fffff") // Get all vertices vertices, err := cell.Vertexes() if err != nil { panic(err) } fmt.Printf("Cell boundary vertices:\n") for i, vertex := range vertices { if !vertex.IsValid() { fmt.Printf(" Vertex %d: INVALID\n", i) continue } latLng, _ := vertex.LatLng() fmt.Printf(" Vertex %d: %v\n", i, latLng) } } ``` -------------------------------- ### Iterate Through All H3 Resolutions Source: https://github.com/uber/h3-go/blob/master/_autodocs/README.md Provides an example of iterating through all available H3 resolutions, from 0 to the maximum, and printing the number of cells at each resolution. ```go for res := 0; res <= h3.MaxResolution; res++ { count := h3.NumCells(res) fmt.Printf("Resolution %d: %d cells\n", res, count) } ``` -------------------------------- ### Get Cells within Grid Distance k (Receiver Method) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use the receiver method Cell.GridDisk for a more concise way to get cells within a specified grid distance from an origin cell. It behaves identically to the GridDisk function. ```go origin := h3.CellFromString("8928308280fffff") neighbors, err := origin.GridDisk(2) if err != nil { panic(err) } fmt.Printf("Found %d neighbors\n", len(neighbors)) ``` -------------------------------- ### Get Origin of Directed Edge in Go Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/edges-and-neighbors.md Use DirectedEdge.Origin to retrieve the starting cell of a directed edge. An error is returned if the provided directed edge is invalid. ```go edge := h3.DirectedEdgeFromString("2234567890abcdef") origin, err := edge.Origin() if err != nil { panic(err) } fmt.Printf("Edge origin: %s\n", origin) ``` -------------------------------- ### H3 Coordinate Conversion Constants Source: https://github.com/uber/h3-go/blob/master/_autodocs/constants.md Provides examples of using constants for converting between kilometers and radians, and degrees and radians for H3 coordinate systems. ```go radiusKm := 100.0 radiusRads := radiusKm / 6371.0 // Using EARTH_RADIUS_KM value // Or use constants radiusRads := radiusKm / 6371.0 angleDegrees := angleDegrees * h3.RadsToDegs angleRadians := angleDegrees * h3.DegsToRads ``` -------------------------------- ### Get Cells Grouped by Distance from Origin (Receiver Method) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use the receiver method Cell.GridDiskDistances for a concise way to get cells within a maximum grid distance k, grouped by their exact distance from the origin. It behaves identically to the GridDiskDistances function. ```go func (c Cell) GridDiskDistances(k int) ([][]Cell, error) ``` -------------------------------- ### Work with H3 Cell Hierarchy Source: https://github.com/uber/h3-go/blob/master/_autodocs/QUICKSTART.md Navigate the H3 hierarchy by finding parent cells, listing children at a specific resolution, or getting the center child. ```go // Get immediate parent child := h3.CellFromString("8928308280fffff") // Resolution 9 parent, _ := child.ImmediateParent() // Resolution 8 fmt.Printf("Parent: %s\n", parent) // Get all children at a resolution grandchildren, _ := parent.Children(11) fmt.Printf("Parent has %d grandchildren\n", len(grandchildren)) // Get center child center, _ := parent.CenterChild(9) fmt.Printf("Center: %s\n", center) ``` -------------------------------- ### Coordinate Conversion Example Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/local-coordinates.md Demonstrates converting between H3 cells and local IJ coordinates for various neighbors relative to an origin. It shows converting to local IJ, then back to an H3 cell, verifying the round trip. ```go package main import ( "fmt" "github.com/uber/h3-go/v4" ) func main() { origin := h3.CellFromString("8928308280fffff") // Explore neighbors via local coordinates coordinates := []h3.CoordIJ{ {0, 0}, // Origin {1, 0}, // East {-1, 0}, // West {0, 1}, // Northeast {0, -1}, // Southwest {1, 1}, // North {-1, -1}, // South } for _, coord := range coordinates { cell, err := h3.LocalIJToCell(origin, coord) if err != nil { fmt.Printf("(%d, %d): error - %v\n", coord.I, coord.J, err) continue } fmt.Printf("(%d, %d): %s\n", coord.I, coord.J, cell) // Convert back ij, _ := h3.CellToLocalIJ(origin, cell) fmt.Printf(" -> back to (%d, %d)\n", ij.I, ij.J) } } ``` -------------------------------- ### Get Immediate Parent Cell Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/cell-hierarchy.md Use `Cell.ImmediateParent` to get the parent cell that is one resolution level up. This is useful for quickly moving up the hierarchy. ```go cell := h3.CellFromString("8928308280fffff") // resolution 9 parent, err := cell.ImmediateParent() if err != nil { panic(err) } fmt.Printf("Immediate parent: %s (res %d)\n", parent, parent.Resolution()) ``` -------------------------------- ### Get Immediate Children Cells Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/cell-hierarchy.md Use `Cell.ImmediateChildren` to get all direct children of a cell, one resolution level down. This typically returns 7 cells for hexagons and 6 for pentagons. ```go parent := h3.CellFromString("89283482ffffff") // resolution 8 children, err := parent.ImmediateChildren() if err != nil { panic(err) } fmt.Printf("Parent has %d immediate children\n", len(children)) for _, child := range children { fmt.Printf(" %s\n", child) } ``` -------------------------------- ### Get All Resolution 0 Cells Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Retrieves all 122 base cells at resolution 0. This function is unlikely to fail. ```go baseCells, err := h3.Res0Cells() if err != nil { panic(err) } fmt.Printf("Found %d base cells\n", len(baseCells)) ``` -------------------------------- ### Calculate Cell Area in Square Meters (Go) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/geometric-measurements.md Use CellAreaM2 to get the exact area of an H3 cell in square meters. It returns an error if the cell is invalid. ```go cell := h3.CellFromString("8928308280fffff") area, err := h3.CellAreaM2(cell) if err != nil { panic(err) } fmt.Printf("Cell area: %.2f m²\n", area) ``` -------------------------------- ### Get Cells within Grid Distance k (Safe) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use GridDiskDistancesSafe for guaranteed correct results, even when pentagons are involved. This function is slower than the unsafe version but ensures accuracy. ```go func GridDiskDistancesSafe(origin Cell, k int) ([][]Cell, error) ``` ```go origin := h3.CellFromString("8928308280fffff") // Guaranteed safe even near pentagons rings, err := h3.GridDiskDistancesSafe(origin, 2) if err != nil { panic(err) } ``` -------------------------------- ### Get Vertex Resolution Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md The Resolution method returns the resolution level (0-15) of a Vertex. ```go func (v Vertex) Resolution() int ``` -------------------------------- ### Get Cells at Exact Grid Distance k (Unsafe) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use GridRingUnsafe for a faster retrieval of cells at an exact grid distance k, but only when you are certain that no pentagons are involved. Behavior is undefined if the origin or any returned cell is a pentagon. ```go func GridRingUnsafe(origin Cell, k int) ([]Cell, error) ``` ```go origin := h3.CellFromString("8928308280fffff") // Fast version for known non-pentagon areas neighbors, err := h3.GridRingUnsafe(origin, 1) if err != nil { panic(err) } fmt.Printf("Found %d neighbors\n", len(neighbors)) ``` -------------------------------- ### Get Cells within Grid Distance k in Parallel Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use GridDisksUnsafe to efficiently compute disks for multiple origin cells in parallel. The outer slice order matches the input origins, but inner slices are unordered. Handles invalid origins or negative k values. ```go origins := []h3.Cell{ h3.CellFromString("8928308280fffff"), h3.CellFromString("8928308281fffff"), } results, err := h3.GridDisksUnsafe(origins, 1) if err != nil { panic(err) } for i, disk := range results { fmt.Printf("Origin %d has %d neighbors\n", i, len(disk)) } ``` -------------------------------- ### Reverse a Directed Edge in Go Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/edges-and-neighbors.md Use the Reverse() method to get the same directed edge with its origin and destination swapped. This is useful when you need to operate on an edge in the opposite direction. ```go edge := h3.DirectedEdgeFromString("2234567890abcdef") reverse, err := edge.Reverse() if err != nil { panic(err) } origin1, _ := edge.Origin() dest1, _ := reverse.Origin() fmt.Printf("Original origin: %s\n", origin1) fmt.Printf("Reversed origin: %s\n", dest1) ``` -------------------------------- ### Get Cells within Grid Distance k Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use GridDisk to find all cells within a specified grid distance from an origin cell. The output is unordered and may contain zeros near pentagons. k=0 returns the origin cell, k=1 returns the origin and its neighbors. ```go package main import ( "fmt" "github.com/uber/h3-go/v4" ) func main() { origin := h3.CellFromString("8928308280fffff") // Get all cells within distance 2 neighbors, err := h3.GridDisk(origin, 2) if err != nil { panic(err) } fmt.Printf("Found %d cells\n", len(neighbors)) } ``` -------------------------------- ### Get Boundary Coordinates of a Directed Edge in Go Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/edges-and-neighbors.md Retrieve the geographic boundary coordinates of a directed edge using the Boundary() method. This may return multiple points if the edge crosses icosahedron faces. ```go origin := h3.CellFromString("8928308280fffff") edges, _ := origin.DirectedEdges() if len(edges) > 0 { boundary, err := edges[0].Boundary() if err != nil { panic(err) } fmt.Printf("Edge has %d boundary points\n", len(boundary)) for i, point := range boundary { fmt.Printf(" Point %d: %v\n", i, point) } } ``` -------------------------------- ### Get Average Hexagon Edge Length in Meters (Go) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/geometric-measurements.md Use HexagonEdgeLengthAvgM to find the average edge length for hexagons at a given resolution in meters. It returns an error for invalid resolutions. ```go length, _ := h3.HexagonEdgeLengthAvgM(15) fmt.Printf("Smallest average edge length: %.3f m\n", length) ``` -------------------------------- ### Get Pentagon Cells at a Specific Resolution Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Use the Pentagons function to retrieve all 12 pentagon cells for a given H3 resolution. Ensure the resolution is within the valid domain (0-15). ```go pentagons, err := h3.Pentagons(9) if err != nil { panic(err) } fmt.Printf("Found %d pentagons at resolution 9\n", len(pentagons)) for _, p := range pentagons { fmt.Println(p) } ``` -------------------------------- ### Convert H3 Vertex to LatLng (Receiver Method) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/coordinate-conversion.md This is a receiver method variant of VertexToLatLng. Call LatLng() on a Vertex object to get its geographic coordinates. Ensure the vertex is valid. ```go vertex := h3.VertexFromString("1234567890abcdef") coords, err := vertex.LatLng() if err != nil { panic(err) } fmt.Println(coords) ``` -------------------------------- ### Calculate Cell Area in Square Kilometers (Go) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/geometric-measurements.md Use CellAreaKm2 to get the exact area of an H3 cell in square kilometers. It returns an error if the cell is invalid. ```go cell := h3.CellFromString("8928308280fffff") area, err := h3.CellAreaKm2(cell) if err != nil { panic(err) } fmt.Printf("Cell area: %.4f km²\n", area) ``` -------------------------------- ### Get Average Hexagon Edge Length in Kilometers (Go) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/geometric-measurements.md Use HexagonEdgeLengthAvgKm to find the average edge length for hexagons at a given resolution in kilometers. It returns an error for invalid resolutions. ```go length, _ := h3.HexagonEdgeLengthAvgKm(9) fmt.Printf("Average edge length at resolution 9: %.2f km\n", length) ``` -------------------------------- ### Get Cells within Grid Distance k (Unsafe) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Use GridDiskDistancesUnsafe for performance-critical applications where you can guarantee no pentagons are involved in the result area. Behavior is undefined if the origin or any returned cell is a pentagon. ```go func GridDiskDistancesUnsafe(origin Cell, k int) ([][]Cell, error) ``` ```go origin := h3.CellFromString("8928308280fffff") // Fast version - only use if you're certain no pentagons are involved rings, err := h3.GridDiskDistancesUnsafe(origin, 2) if err != nil { panic(err) } fmt.Printf("Got %d rings\n", len(rings)) ``` -------------------------------- ### Get Shortest Path Between Two H3 Cells Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Returns all cells in the shortest path between two H3 cells, inclusive. This function may fail for cells that are very far apart or on opposite sides of a pentagon. Ensure cells are at the same resolution. ```Go package main import ( "fmt" "github.com/uber/h3-go/v3" ) func main() { start := h3.CellFromString("8928308280fffff") end := h3.CellFromString("8928308281fffff") path, err := h3.GridPath(start, end) if err != nil { fmt.Printf("Could not compute path: %v\n", err) return } fmt.Printf("Path has %d cells\n", len(path)) for i, cell := range path { fmt.Printf(" Step %d: %s\n", i, cell) } } ``` -------------------------------- ### Hello World: Convert LatLng to H3 Cell Source: https://github.com/uber/h3-go/blob/master/_autodocs/README.md Demonstrates basic usage by converting geographic coordinates to an H3 cell index at a specified resolution. Requires importing the h3 package. ```go package main import ( "fmt" h3 "github.com/uber/h3-go/v4" ) func main() { // Create a geographic point latLng := h3.NewLatLng(37.775938728915946, -122.41795063018799) // Get H3 cell at resolution 9 cell, err := h3.LatLngToCell(latLng, 9) if err != nil { panic(err) } fmt.Println(cell) // 8928308280fffff } ``` -------------------------------- ### Apply VSCode Configuration Source: https://github.com/uber/h3-go/blob/master/CONTRIBUTING.md Applies VSCode-specific configurations, potentially via git cherry-pick. ```bash git cherry-pick vscode ``` -------------------------------- ### Get All Children Cells at Specific Resolution Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/cell-hierarchy.md Use `Cell.Children` to retrieve all child cells at a resolution higher than the current cell's resolution. Each cell typically has 7 children, or 6 for pentagons. This can also retrieve grandchildren. ```go parent := h3.CellFromString("89283482ffffff") // resolution 8 // Get all children at resolution 10 children, err := parent.Children(10) if err != nil { panic(err) } fmt.Printf("Parent has %d children at resolution 10\n", len(children)) ``` -------------------------------- ### Get Vertex Index Digit Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md Use IndexDigit to get the indexing digit of a Vertex at a specific resolution. It returns the digit value (0-7) or an error if the resolution is invalid. ```go func (v Vertex) IndexDigit(resolution int) (int, error) ``` -------------------------------- ### Run Tests Source: https://github.com/uber/h3-go/blob/master/CONTRIBUTING.md Executes all unit tests for the H3-Go library. ```bash go test ``` -------------------------------- ### Get all vertices using Cell receiver method Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md The Cell.Vertexes method offers a receiver-based approach to get all vertices of an H3 cell, equivalent to the standalone CellToVertexes function. ```go cell := h3.CellFromString("8928308280fffff") vertices, err := cell.Vertexes() if err != nil { panic(err) } for _, v := range vertices { fmt.Printf("%s: %v\n", v, v.LatLng()) } ``` -------------------------------- ### Generate Coverage Report Source: https://github.com/uber/h3-go/blob/master/CONTRIBUTING.md Generates a code coverage profile and opens it in an HTML browser. ```bash go test -coverprofile=covprofile && go tool cover -html=covprofile ``` -------------------------------- ### Get a specific vertex of an H3 cell Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md Use CellToVertex to get a vertex at a specific position (0-5 for hexagons, 0-4 for pentagons) of an H3 cell. Ensure the cell and vertex number are valid. ```go package main import ( "fmt" "github.com/uber/h3-go/v4" ) func main() { cell := h3.CellFromString("8928308280fffff") // Get the first vertex vertex, err := h3.CellToVertex(cell, 0) if err != nil { panic(err) } // Get coordinates latLng, _ := vertex.LatLng() fmt.Printf("Vertex 0: %v\n", latLng) } ``` -------------------------------- ### Run Linter Source: https://github.com/uber/h3-go/blob/master/CONTRIBUTING.md Runs the golangci-lint tool to check for code style and potential issues. ```bash golangci-lint run ``` -------------------------------- ### Safe vs Unsafe GridDisk Function Variants Source: https://github.com/uber/h3-go/blob/master/_autodocs/errors.md Illustrates the difference between safe and unsafe grid functions, highlighting automatic pentagon handling in safe variants. ```go // Safe: handles pentagons automatically cells, err := h3.GridDiskDistances(origin, 2) if err != nil { // Handle error } ``` ```go // Unsafe: undefined behavior near pentagons cells, err := h3.GridDiskDistancesUnsafe(origin, 2) if err != nil { // Only returns error for invalid input } ``` -------------------------------- ### Pre-allocating H3 Cell Boundary Slice Source: https://github.com/uber/h3-go/blob/master/_autodocs/constants.md Shows how to pre-allocate a slice for an H3 cell boundary with a capacity equal to the maximum possible vertices for a cell, optimizing performance. ```go var boundary h3.CellBoundary boundary = make([]h3.LatLng, 0, h3.MaxCellBndryVerts) ``` -------------------------------- ### Get H3 DirectedEdge Resolution Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Retrieves the resolution level (0-15) of an H3 DirectedEdge. ```go func (e DirectedEdge) Resolution() int ``` -------------------------------- ### Convert H3 Cell to Coordinates Source: https://github.com/uber/h3-go/blob/master/_autodocs/QUICKSTART.md Get the geographic coordinates of the center of an H3 cell. ```go // Get the center point of a cell cell := h3.CellFromString("8928308280fffff") latLng, err := cell.LatLng() if err != nil { log.Fatal(err) } fmt.Printf("Center: %.4f, %.4f\n", latLng.Lat, latLng.Lng) ``` -------------------------------- ### DirectedEdge.Origin Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/edges-and-neighbors.md Returns the origin Cell of a directed edge. This method returns the cell where the edge starts. ```APIDOC ## DirectedEdge.Origin ### Description Returns the origin Cell of a directed edge. ### Method ```go func (e DirectedEdge) Origin() (Cell, error) ``` ### Returns - **Cell**: The cell where the edge starts - **error**: `ErrDirectedEdgeInvalid` if edge is invalid ### Example ```go edge := h3.DirectedEdgeFromString("2234567890abcdef") origin, err := edge.Origin() if err != nil { panic(err) } fmt.Printf("Edge origin: %s\n", origin) ``` ``` -------------------------------- ### Convert Latitude/Longitude to H3 Cell Source: https://github.com/uber/h3-go/blob/master/README.md Demonstrates converting a latitude and longitude to an H3 cell index at a specified resolution. Ensure H3-Go is imported. ```go 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 } ``` -------------------------------- ### Get String Representation of H3 Cell Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-serialization.md Returns the lowercase hexadecimal string representation of an H3 Cell. ```go cell := h3.CellFromString("8928308280fffff") fmt.Println(cell.String()) // Output: 8928308280fffff ``` -------------------------------- ### GridPath Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Returns all cells in the shortest path between two H3 cells, inclusive of the start and end cells. ```APIDOC ## GridPath ### Description Returns all cells in the shortest path between two cells (inclusive). ### Function Signature ```go func GridPath(a, b Cell) ([]Cell, error) ``` ### Parameters #### Path Parameters - **a** (Cell) - Required - Starting cell - **b** (Cell) - Required - Ending cell ### Returns - **[]Cell**: Cells from a to b inclusive - **error**: May fail for cells very far apart or on opposite sides of a pentagon ### Example ```go start := h3.CellFromString("8928308280fffff") end := h3.CellFromString("8928308281fffff") path, err := h3.GridPath(start, end) if err != nil { fmt.Printf("Could not compute path: %v\n", err) return } fmt.Printf("Path has %d cells\n", len(path)) for i, cell := range path { fmt.Printf(" Step %d: %s\n", i, cell) } ``` ``` -------------------------------- ### Validating H3 Index Source: https://github.com/uber/h3-go/blob/master/_autodocs/constants.md Illustrates how to check if an H3 index is invalid (null) using the `h3.InvalidH3Index` constant. ```go if index == h3.InvalidH3Index { fmt.Println("Index is null") } ``` -------------------------------- ### Handle H3 Coordinate Conversion Errors Source: https://github.com/uber/h3-go/blob/master/_autodocs/README.md Demonstrates how to handle potential errors when converting latitude/longitude to an H3 cell, such as invalid coordinates or resolutions. ```go cell, err := h3.LatLngToCell(latLng, 9) if err != nil { switch err { case h3.ErrLatLngDomain: // Coordinates out of range case h3.ErrResolutionDomain: // Resolution out of range default: // Other errors } } ``` -------------------------------- ### Get H3 Cell Neighbors Source: https://github.com/uber/h3-go/blob/master/_autodocs/QUICKSTART.md Retrieve all H3 cells that are neighbors to a given cell within a specified distance. ```go cell := h3.CellFromString("8928308280fffff") // Get all cells within distance 1 neighbors, err := cell.GridRing(1) if err != nil { log.Fatal(err) } fmt.Printf("Found %d neighbors\n", len(neighbors)) ``` -------------------------------- ### Vertex Type Methods Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md Provides methods for interacting with Vertex objects, including obtaining their string representation, marshaling for storage or transfer, and retrieving specific properties. ```APIDOC ## Vertex Methods ### Vertex.String #### Description Returns the lowercase hexadecimal string representation of a Vertex. This is useful for logging, debugging, or simple identification. #### Function Signature ```go func (v Vertex) String() string ``` #### Returns - **string**: The lowercase hexadecimal string of the Vertex. ### Vertex.MarshalText #### Description Encodes a Vertex into a UTF-8 byte slice, typically for JSON or text marshaling. This method is designed to be efficient and never returns an error. #### Function Signature ```go func (v Vertex) MarshalText() ([]byte, error) ``` #### Returns - **[]byte**: A byte slice containing the UTF-8 encoded hexadecimal string of the Vertex. - **error**: This method is designed to never return an error. ### Vertex.UnmarshalText #### Description Decodes a Vertex from a byte slice, commonly used during JSON or text unmarshaling. It validates the input and returns an error if the provided text does not represent a valid Vertex. #### Function Signature ```go func (v *Vertex) UnmarshalText(text []byte) error ``` #### Parameters - **text** ([]byte) - Required - The byte slice containing the text representation of the Vertex. #### Returns - **error**: An error if the parsed value is not a valid vertex; otherwise, `nil`. ### Vertex.Resolution #### Description Retrieves the H3 resolution level at which this Vertex is defined. Vertexes are associated with a specific resolution based on the cell they belong to. #### Function Signature ```go func (v Vertex) Resolution() int ``` #### Returns - **int**: The resolution level of the Vertex, ranging from 0 to 15. ### Vertex.IndexDigit #### Description Returns the indexing digit for a Vertex at a specified resolution. This digit indicates the position of the vertex relative to the center of the H3 cell. #### Function Signature ```go func (v Vertex) IndexDigit(resolution int) (int, error) ``` #### Parameters - **resolution** (int) - Required - The resolution at which to determine the index digit. #### Returns - **int**: The digit value (0-7) representing the vertex's position. - **error**: An error if the provided resolution is invalid. ``` -------------------------------- ### Hierarchy Navigation Functions Source: https://github.com/uber/h3-go/blob/master/_autodocs/INDEX.md Functions for navigating the H3 hierarchy, finding parent cells, children cells, and compacting cell sets. ```APIDOC ## Cell.Parent() ### Description Gets the parent H3 cell of the current cell at a specified resolution. ### Method `Cell.Parent(resolution)` ### Parameters - **resolution** (int) - The desired parent resolution. ### Response - **Cell**: The parent H3 cell. ## Cell.Children() ### Description Gets all direct children H3 cells of the current cell at a specified resolution. ### Method `Cell.Children(resolution)` ### Parameters - **resolution** (int) - The desired children resolution. ### Response - **[]Cell**: A slice of direct children H3 cells. ## CompactCells() ### Description Compacts a set of H3 cells into a smaller set of larger H3 cells that cover the same area. ### Method `CompactCells(cells)` ### Parameters - **cells** ([]Cell) - The set of H3 cells to compact. ### Response - **[]Cell**: The compacted set of H3 cells. ``` -------------------------------- ### Get Base Cell Number for any H3 Cell Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Returns the base cell number (0-121) for any given H3 Cell. ```go func BaseCellNumber(h Cell) int ``` -------------------------------- ### GeoPolygon Type Source: https://github.com/uber/h3-go/blob/master/_autodocs/types.md Defines a geographic polygon with an outer boundary and optional holes. It provides a method to get cells within the polygon. ```APIDOC ## GeoPolygon Type ### Description A geographic polygon with one outer boundary and zero or more holes, following GeoJSON MultiPolygon order. | Field | Type | Required | Description | |-------|------|----------|-------------| | GeoLoop | GeoLoop | Yes | Outer boundary loop | | Holes | []GeoLoop | No | Interior holes | ### Methods - `GeoPolygon.Cells(resolution int) ([]Cell, error)` - Get cells within polygon **Used by:** - `PolygonToCells()`, `PolygonToCellsExperimental()` - `CellsToMultiPolygon() ``` -------------------------------- ### Get Cell Position Among Children Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/cell-hierarchy.md Returns the position of a cell within the ordered list of all children of its parent. The position is zero-indexed. ```go child := h3.CellFromString("8928308280fffff") // resolution 9 // Find its position in resolution 8 parent's children pos, err := h3.CellToChildPos(child, 8) if err != nil { panic(err) } fmt.Printf("Cell is at position %d in its parent's children\n", pos) ``` -------------------------------- ### Validate User Input for H3 Cells Source: https://github.com/uber/h3-go/blob/master/_autodocs/README.md Shows how to validate a user-provided string to ensure it represents a valid H3 cell before further processing. ```go cell := h3.CellFromString(userInput) if !cell.IsValid() { fmt.Println("Invalid cell") return } ``` -------------------------------- ### Conversion Constants Source: https://github.com/uber/h3-go/blob/master/_autodocs/types.md Provides constants for converting between degrees and radians. ```APIDOC ## Conversion Constants | Constant | Value | Description | |----------|-------|-------------| | DegsToRads | π/180.0 | Degrees to radians multiplier | | RadsToDegs | 180.0/π | Radians to degrees multiplier | ``` -------------------------------- ### Get H3 Cell Resolution Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Retrieves the resolution level (0-15) of an H3 Cell. This function works on any Cell value, regardless of its validity. ```go cell := h3.CellFromString("8928308280fffff") res := cell.Resolution() fmt.Printf("Cell resolution: %d\n", res) ``` -------------------------------- ### Get H3 Cell Boundary Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/coordinate-conversion.md Retrieves the boundary of an H3 cell as a slice of LatLng points. Ensure the H3 cell is valid before calling. ```go cell := h3.CellFromString("8928308280fffff") boundary, err := cell.Boundary() if err != nil { panic(err) } for i, v := range boundary { fmt.Printf("Vertex %d: %v\n", i, v) } ``` -------------------------------- ### Get H3 Cell Boundary Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/coordinate-conversion.md Retrieves the boundary vertices of an H3 cell as a slice of LatLng points. Ensure the cell index is valid. ```go cell := h3.CellFromString("8928308280fffff") boundary, err := h3.CellToBoundary(cell) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Cell has %d vertices:\n", len(boundary)) for _, vertex := range boundary { fmt.Printf(" %v\n", vertex) } ``` -------------------------------- ### GridDiskDistancesSafe Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/grid-navigation.md Produces cells within grid distance k, grouped by distance. This is a safe version that handles pentagons correctly, though it is slower than the unsafe variant. ```APIDOC ## GridDiskDistancesSafe ### Description Produces cells within grid distance k, grouped by distance (safe with pentagons). ### Method ```go func GridDiskDistancesSafe(origin Cell, k int) ([][]Cell, error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | origin | Cell | Yes | — | Starting cell | | k | int | Yes | — | Maximum grid distance | ### Returns: - `[][]Cell`: Result[i] contains cells at distance i (k+1 slices total) - `error`: `ErrCellInvalid` if origin is invalid; `ErrDomain` if k is negative ### Notes: - Always produces correct results, even with pentagons - Slower than GridDiskDistancesUnsafe - GridDiskDistances automatically switches to this when needed ### Example: ```go origin := h3.CellFromString("8928308280fffff") // Guaranteed safe even near pentagons rings, err := h3.GridDiskDistancesSafe(origin, 2) if err != nil { panic(err) } ``` ``` -------------------------------- ### GreatCircleDistanceKm Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/geometric-measurements.md Computes the great circle distance between two points in kilometers. This function provides a convenient way to get distances in a commonly used unit. ```APIDOC ## GreatCircleDistanceKm ### Description Computes the great circle distance between two geographic points in kilometers. This function is useful for applications requiring distances in a standard metric unit. ### Method `func GreatCircleDistanceKm(a, b LatLng) float64` ### Parameters #### Path Parameters - **a** (LatLng) - Yes - First geographic point - **b** (LatLng) - Yes - Second geographic point ### Returns - `float64`: Distance in kilometers ### Example ```go london := h3.NewLatLng(51.5074, -0.1278) paris := h3.NewLatLng(48.8566, 2.3522) distKm := h3.GreatCircleDistanceKm(london, paris) fmt.Printf("Distance: %.2f km\n", distKm) ``` ``` -------------------------------- ### Cell Validation Pattern Source: https://github.com/uber/h3-go/blob/master/_autodocs/errors.md Demonstrates how to validate a cell obtained from a string and handle potential errors during coordinate retrieval. ```go cell := h3.CellFromString("invalid") if !cell.IsValid() { fmt.Println("Cell is not valid") return } latLng, err := cell.LatLng() if err != nil { fmt.Printf("Operation failed: %v\n", err) } ``` -------------------------------- ### Cell.Children Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/cell-hierarchy.md Returns all children of this cell at a specified resolution. The child resolution must be greater than the current resolution, and can skip multiple levels to get grandchildren. ```APIDOC ## Cell.Children ### Description Returns all children of this cell at a specified resolution. The child resolution must be greater than the current resolution, and can skip multiple levels to get grandchildren. ### Method func (c Cell) Children(resolution int) ([]Cell, error) ### Parameters #### Path Parameters - **resolution** (int) - Required - Child resolution (must be > current resolution) ### Returns - **[]Cell**: All child cells at the specified resolution - **error**: `ErrResolutionDomain` if resolution invalid; `ErrCellInvalid` if cell invalid ### Notes - Each cell has 7 children (hexagons) or 6 children (pentagons) - Can skip multiple levels to get grandchildren - Resolution 15 has no children (maximum resolution) ``` -------------------------------- ### Vertex.LatLng Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/coordinate-conversion.md Receiver method variant of VertexToLatLng. ```APIDOC ## Vertex.LatLng ### Description Receiver method variant of VertexToLatLng. ### Method ```go func (v Vertex) LatLng() (LatLng, error) ``` ### Response #### Success Response - **LatLng**: Geographic coordinates of the vertex in degrees - **error**: Same as VertexToLatLng ### Request Example ```go vertex := h3.VertexFromString("1234567890abcdef") coords, err := vertex.LatLng() if err != nil { panic(err) } fmt.Println(coords) ``` ``` -------------------------------- ### Parse H3 Index from Hex String Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-serialization.md Parses a hexadecimal string into a 64-bit H3 index. Accepts optional '0x' or '0X' prefixes and is case-insensitive. Returns 0 on parsing failure and does not validate the index. ```go package main import ( "fmt" "github.com/uber/h3-go/v4" ) func main() { // Both formats work idx1 := h3.IndexFromString("8928308280fffff") idx2 := h3.IndexFromString("0x8928308280fffff") idx3 := h3.IndexFromString("0X8928308280FFFFF") // case-insensitive fmt.Printf("Parsed: %016x\n", idx1) fmt.Printf("Parsed: %016x\n", idx2) fmt.Printf("Parsed: %016x\n", idx3) } ``` -------------------------------- ### Convert H3 Cell to LatLng Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/coordinate-conversion.md Use this function to get the geographic center coordinates of an H3 cell. Ensure the provided cell index is valid. ```go cell := h3.Cell(0x8928308280fffff) latLng, err := h3.CellToLatLng(cell) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Center: %v\n", latLng) // Output: Center: (37.77593, -122.41795) ``` -------------------------------- ### Error Type Checking with Switch Statement Source: https://github.com/uber/h3-go/blob/master/_autodocs/errors.md Shows how to check for specific H3 error types using a switch statement after an operation fails. ```go _, err := h3.LatLngToCell(badLatLng, 9) if err != nil { switch err { case h3.ErrLatLngDomain: fmt.Println("Coordinates out of range") case h3.ErrResolutionDomain: fmt.Println("Resolution out of range") case h3.ErrFailed: fmt.Println("Unknown error") } } ``` -------------------------------- ### Get String Representation of H3 Vertex Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-serialization.md Returns the string representation of an H3 Vertex as a lowercase hexadecimal string. Use this for displaying or logging vertex indices. ```go func (v Vertex) String() string ``` -------------------------------- ### Get Destination of Directed Edge in Go Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/edges-and-neighbors.md Use DirectedEdge.Destination to retrieve the ending cell of a directed edge. An error is returned if the provided directed edge is invalid. ```go edge := h3.DirectedEdgeFromString("2234567890abcdef") dest, err := edge.Destination() if err != nil { panic(err) } fmt.Printf("Edge destination: %s\n", dest) ``` -------------------------------- ### Get Icosahedron Faces Intersected by H3 Cell Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Returns the icosahedron face numbers (0-19) that a given H3 Cell overlaps. Returns an error if the cell is invalid. ```go cell := h3.CellFromString("8928308280fffff") faces, err := cell.IcosahedronFaces() if err != nil { panic(err) } fmt.Printf("Cell intersects faces: %v\n", faces) ``` -------------------------------- ### IndexFromString Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-serialization.md Parses a hexadecimal string representation into a 64-bit H3 index value. It handles optional '0x' prefixes and is case-insensitive. Note that this function does not validate the index; `IsValid()` should be called separately. ```APIDOC ## IndexFromString ### Description Parses a hex string to a 64-bit index value. ### Method Signature ```go func IndexFromString(s string) uint64 ``` ### Parameters #### Path Parameters - **s** (string) - Required - Hexadecimal string (with optional "0x" prefix) ### Returns - **uint64**: Parsed index value ### Notes - Accepts optional "0x" or "0X" prefix - Case-insensitive hex parsing - Returns 0 if parsing fails (silent failure) - Does not validate the index; use `IsValid()` after parsing ### Example ```go package main import ( "fmt" "github.com/uber/h3-go/v4" ) func main() { // Both formats work idx1 := h3.IndexFromString("8928308280fffff") idx2 := h3.IndexFromString("0x8928308280fffff") idx3 := h3.IndexFromString("0X8928308280FFFFF") // case-insensitive fmt.Printf("Parsed: %016x\n", idx1) fmt.Printf("Parsed: %016x\n", idx2) fmt.Printf("Parsed: %016x\n", idx3) } ``` ``` -------------------------------- ### Get a specific vertex using Cell receiver method Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/vertices.md The Cell.Vertex method provides a receiver-based alternative to CellToVertex for obtaining a vertex at a specific position from an H3 cell. ```go cell := h3.CellFromString("8928308280fffff") vertex, err := cell.Vertex(2) if err != nil { panic(err) } fmt.Printf("Vertex 2: %s\n", vertex) ``` -------------------------------- ### ErrResolutionDomain Go Error Definition Source: https://github.com/uber/h3-go/blob/master/_autodocs/errors.md Defines an error for resolution arguments outside acceptable ranges. This occurs when resolution is less than 0 or greater than the maximum resolution (15). ```go var ErrResolutionDomain = errors.New("resolution argument was outside of acceptable range") ``` -------------------------------- ### Create Directed Edge in Go Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/edges-and-neighbors.md Use Cell.DirectedEdge to create a directed edge between two adjacent cells. The destination cell must be a direct neighbor of the origin cell. Errors are returned for invalid cells or non-neighboring cells. ```go origin := h3.CellFromString("8928308280fffff") // Get all edges from this cell edges, _ := origin.DirectedEdges() if len(edges) > 0 { // Get the origin and destination dest, _ := edges[0].Destination() fmt.Printf("Origin: %s\n", origin) fmt.Printf("Destination: %s\n", dest) // Create edge back reverseEdge, _ := dest.DirectedEdge(origin) fmt.Printf("Reverse edge: %s\n", reverseEdge) } ``` -------------------------------- ### Get String Representation of H3 DirectedEdge Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-serialization.md Returns the string representation of an H3 DirectedEdge as a lowercase hexadecimal string. This is useful for displaying or logging directed edge indices. ```go func (e DirectedEdge) String() string ``` -------------------------------- ### Handle H3-Go Errors Source: https://github.com/uber/h3-go/blob/master/_autodocs/QUICKSTART.md Demonstrates how to check for and handle errors returned by H3-Go functions, such as invalid coordinates or resolutions. Use a switch statement to differentiate between specific error types. ```go cell, err := h3.LatLngToCell(latLng, 9) if err != nil { switch err { case h3.ErrLatLngDomain: fmt.Println("Bad coordinates") case h3.ErrResolutionDomain: fmt.Println("Bad resolution") default: fmt.Println(err) } } ``` -------------------------------- ### Calculate Directed Edge Length in Meters (Go) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/geometric-measurements.md Use EdgeLengthM to calculate the exact length of a directed H3 edge in meters. It returns an error if the edge is invalid. ```go origin := h3.CellFromString("8928308280fffff") edges, _ := origin.DirectedEdges() if len(edges) > 0 { length, _ := h3.EdgeLengthM(edges[0]) fmt.Printf("Edge length: %.2f m\n", length) } ``` -------------------------------- ### Convert Polygon to H3 Cells (Experimental) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/polygon-operations.md Converts a polygon to H3 cells using experimental containment modes (center, full, overlapping, overlapping bbox) and an optional maximum cell count. Useful for fine-grained control over cell inclusion. ```go polygon := h3.GeoPolygon{ GeoLoop: []h3.LatLng{ h3.NewLatLng(37.0, -122.0), h3.NewLatLng(37.0, -121.0), h3.NewLatLng(38.0, -121.0), h3.NewLatLng(38.0, -122.0), h3.NewLatLng(37.0, -122.0), }, } // Get cells fully contained in polygon cells, err := h3.PolygonToCellsExperimental( polygon, 8, h3.ContainmentFull, 1000, // Limit to 1000 cells ) if err != nil { panic(err) } fmt.Printf("Found %d fully-contained cells\n", len(cells)) ``` -------------------------------- ### Pentagons Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/index-properties.md Returns all 12 pentagon cells at a specified resolution. The resolution must be between 0 and 15. ```APIDOC ## Pentagons ### Description Returns all 12 pentagon cells at a specified resolution. ### Function Signature ```go func Pentagons(resolution int) ([]Cell, error) ``` ### Parameters #### Path Parameters - **resolution** (int) - Required - Resolution (0-15). Invalid resolutions will result in an error. ### Returns - **[]Cell**: A slice containing all 12 pentagon cells at the specified resolution. - **error**: Returns `ErrResolutionDomain` if the provided resolution is invalid. ### Example ```go pentagons, err := h3.Pentagons(9) if err != nil { panic(err) } fmt.Printf("Found %d pentagons at resolution 9\n", len(pentagons)) for _, p := range pentagons { fmt.Println(p) } ``` ``` -------------------------------- ### Get Cell Position Among Children (Receiver Method) Source: https://github.com/uber/h3-go/blob/master/_autodocs/api-reference/cell-hierarchy.md Receiver method variant of CellToChildPos. Returns the position of a cell within the ordered list of all children of its parent. ```go child := h3.CellFromString("8928308280fffff") // resolution 9 // Find its position in resolution 8 parent's children pos, err := child.ChildPos(8) if err != nil { panic(err) } fmt.Printf("Cell is at position %d in its parent's children\n", pos) ``` -------------------------------- ### Get H3 Cell Area Source: https://github.com/uber/h3-go/blob/master/_autodocs/QUICKSTART.md Retrieve the exact area of a specific H3 cell in square meters and the average area for cells at a given resolution in square kilometers. ```go cell := h3.CellFromString("8928308280fffff") // Exact area of this specific cell areaM2, err := h3.CellAreaM2(cell) if err != nil { log.Fatal(err) } fmt.Printf("Cell area: %.2f m²\n", areaM2) // Average area for all cells at this resolution avgAreaKm2, _ := h3.HexagonAreaAvgKm2(cell.Resolution()) fmt.Printf("Average area: %.2f km²\n", avgAreaKm2) ```