h3-js

repository·master·Indexed 22 days ago

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

A pure-JavaScript implementation of the H3 hexagon-based geographic grid system, providing full parity with the H3 C API for Node.js and browser environments. It enables converting coordinates to H3 cells, performing spatial operations like polygon filling and neighbor discovery, navigating cell hierarchies, and calculating grid distances, areas, and great circle distances.

Tokens
10.3K
Snippets
38
Records
58
Agent score
77%

What's inside h3-js

  1. Import h3-js

    master

    The library supports ES6 modules, CommonJS, and pre-bundled scripts for the browser.

    ES6 Modules

    Use this for modern JavaScript environments and bundlers.

    CommonJS

    Use this for Node.js environments using require.

    Browser (Pre-bundled)

    Include the script tag to make the h3 global available in your browser environment.

    // ES6 usage
    import {latLngToCell} from "h3-js";
    
    // CommonJS usage
    const h3 = require("h3-js");
    <!-- Pre-bundled script (library is available as an `h3` global) -->
    <script src="https://unpkg.com/h3-js"></script>
  2. Migrate from H3 v3 to H3 v4 using the Legacy API

    master

    H3 v4 introduced breaking changes, including renamed functions. To ease migration, you can use the legacy API wrapper located at h3-js/legacy. This wrapper exports v4 functions using their v3 names.

    Warning: The legacy API is not 100% backwards compatible. It is a thin wrapper on top of v4, meaning v4 behavior (such as throwing errors for invalid input instead of returning null) will be used.

    import {geoToH3} from 'h3-js/legacy';
    
    const h3Index = geoToH3(37.3615593, -122.0553238, 7);
  3. Transpile the C source using Docker

    master

    The core of h3-js is transpiled from C using Emscripten. To build the library from source locally, use Docker to avoid manual Emscripten setup:

    1. Ensure Docker is installed.
    2. Run yarn docker-boot.
    3. Run yarn build-emscripten.

    The build script uses the H3_VERSION file to determine the core library version. To test local changes to the C core, clone the desired H3 repository to ./h3c and run yarn docker-emscripten.

    yarn docker-boot
    yarn build-emscripten
  4. Run benchmarks for performance testing

    master

    Since many H3 functions are called in high-frequency loops, performance is critical. The library includes a benchmark suite using Benchmark.js. You can run benchmarks in different environments using yarn:

    • Node.js: yarn benchmark-node
    • Browser: yarn benchmark-browser

    When making performance-sensitive changes, it is recommended to run benchmarks against the master branch and then against your feature branch to detect regressions.

    yarn benchmark-node
    # or
    yarn benchmark-browser
  5. Use the Legacy API for H3 v3 compatibility

    master

    H3 v4 introduced breaking changes by renaming most functions. To ease migration from H3 v3 to H3 v4, you can use the legacy API wrapper located at h3-js/legacy. This wrapper exports v4 functions using their original v3 names.

    Important Notes:

    • The legacy API is a thin wrapper and is not 100% backwards compatible.
    • If behavior has changed in v4, the v4 behavior will be used.
    • Many v4 functions throw errors for invalid input, whereas the original v3 functions might have returned null.
    import {geoToH3} from 'h3-js/legacy';
    
    const h3Index = geoToH3(37.3615593, -122.0553238, 7);
  6. Legacy mapping for H3 version compatibility

    master
    The lib/legacy-mapping.js file provides a mapping object used to maintain compatibility with older versions of the H3 library. It maps current H3 function names to their legacy counterparts. If you are working with codebases or data formats that expect older H3 function names, this mapping can be used to translate them to the current API surface.
  7. Convert coordinates to H3 cells and back

    master

    Use core functions to convert latitude/longitude points to H3 hexagon indices at a specific resolution, and retrieve the center or boundary coordinates of a hexagon.

    // Convert a lat/lng point to a hexagon index at resolution 7
    const h3Index = h3.latLngToCell(37.3615593, -122.0553238, 7);
    // -> '87283472bffffff'
    
    // Get the center of the hexagon
    const hexCenterCoordinates = h3.cellToLatLng(h3Index);
    // -> [37.35171820183272, -122.05032565263946]
    
    // Get the vertices of the hexagon
    const hexBoundary = h3.cellToBoundary(h3Index);
    // -> [ [37.341099093235684, -122.04156135164334 ], ...]
  8. Use H3 grid and polygon algorithms

    master

    Perform spatial operations such as finding neighboring hexagons, filling a polygon with hexagons, or generating a GeoJSON-style MultiPolygon from a set of cells.

    // Get all neighbors within 1 step of the hexagon
    const disk = h3.gridDisk(h3Index, 1);
    // -> ['87283472bffffff', '87283472affffff', ...]
    
    // Get the set of hexagons within a polygon
    const polygon = [
        [37.813318999983238, -122.4089866999972145],
        [37.7198061999978478, -122.3544736999993603],
        [37.8151571999998453, -122.4798767000009008]
    ];
    const hexagons = h3.polygonToCells(polygon, 7);
    // -> ['872830828ffffff', '87283082effffff', ...]
    
    // Get the outline of a set of hexagons, as a GeoJSON-style MultiPolygon
    const coordinates = h3.cellsToMultiPolygon(hexagons, true);
    // -> [[[ 
    //      [-122.37681938644465, 37.76546768434345],
    //      [-122.3856345540363,37.776004200673846],
    //      ... 
    //    ]]]
  9. Compact and uncompact H3 cell sets

    master

    Optimize a set of hexagons by representing them at different resolutions.

    • h3.compactCells(h3Set): Takes a set of hexagons of the same resolution and returns a new set of hexagons across multiple levels that covers the same area.
    • h3.uncompactCells(compactedSet, res): Expands a compacted set back into a set of hexagons at the specified resolution res.
  10. Get all resolution 0 H3 indexes with getRes0Cells()

    master
    Use h3.getRes0Cells() to get an array of all H3 indexes at resolution 0. Since every index at any resolution greater than 0 is a descendant of a resolution 0 index, you can use these as starting points for h3ToChildren to iterate over the entire H3 grid at any resolution.
  11. Retrieve H3 cell components and metadata

    master

    Extract structural information from an H3 index:

    • h3.getBaseCellNumber(h3Index): Returns the base cell number (0-121).
    • h3.getIndexDigit(h3Index, digit): Returns the value of a specific indexing digit (0-7).
    • h3.getResolution(h3Index): Returns the resolution (0-15), or -1 if invalid.
    • h3.getIcosahedronFaces(h3Index): Returns the indices (0-19) of all intersected icosahedron faces.
    // h3.getBaseCellNumber(h3Index: H3IndexInput) => number
    // h3.getIndexDigit(h3Index: H3IndexInput, digit: number) => number
    // h3.getResolution(h3Index: H3IndexInput) => number
    // h3.getIcosahedronFaces(h3Index: H3IndexInput) => Array<number>