License: Apache 2.0

JavaScript

BGrid for JavaScript

A lightweight, zero-dependency JavaScript library for converting between geographic coordinates and BGrid indices. Supports both ESM and UMD module formats, with built-in BIP39 wordlist helpers for human-readable grid encoding.

Features

  • Zero Dependencies: Pure JavaScript with no external packages.
  • Dual Module Format: Ships both ESM (bgrid.mjs) and UMD (bgrid.umd.js) builds.
  • Small Footprint: ~4-5 KB minified.
  • BIP39 Word Support: Encode and decode grid indices as human-readable words in 5 languages.
  • Hierarchical Grid Queries: Enumerate all cells at any level or within a parent cell.
  • Async Language Loading: Load word lists on demand to minimize initial bundle size.

Installation

npm install @bgrid/bgrid-js

After installation, module entry points are:

FormatPath
ESM@bgrid/bgrid-js/dist/bgrid.mjs
UMD@bgrid/bgrid-js/dist/bgrid.umd.js
Words@bgrid/bgrid-js/bip39-wordlist/bip39-*.json

Quick Start

ES Modules

<script type="module">
  import { coordsToBGrid, bgridToCell, loadLanguage, gridToDisplay }
    from '@bgrid/bgrid-js';

  const grid = coordsToBGrid(40.4168, -3.7038, 4); // Madrid, 4 levels
  console.log('BGrid:', grid);

  const cell = bgridToCell(grid);
  console.log('Center:', cell.lat, cell.lon);
  console.log('Bounds:', cell.bounds);

  const es = await loadLanguage('es');
  console.log('Words:', gridToDisplay(grid, { mode: 'words', words: es }));
</script>

UMD (Browser Global)

<script src="node_modules/@bgrid/bgrid-js/dist/bgrid.umd.js"></script>
<script>
  const grid = BGrid.coordsToBGrid(40.4168, -3.7038, 4);
  const cell = BGrid.bgridToCell(grid);

  BGrid.loadLanguage('es').then(function(es) {
    console.log(BGrid.gridToDisplay(grid, { mode: 'words', words: es }));
  });
</script>

API Reference

coordsToBGrid(lat, lon, levels)

Converts geographic coordinates to a BGrid index array.

coordsToBGrid(lat: number, lon: number, levels: number): number[]
ParameterTypeDescription
latnumberLatitude (-90 to 90), must be finite
lonnumberLongitude (-180 to 180), must be finite
levelsnumberPositive integer for subdivision depth

Returns: Array of grid indices (1–2048 per level).

Throws: Error if inputs are not finite numbers or levels is not a positive integer.


bgridToCell(bgridArray)

Converts a BGrid index array back to geographic bounds and center.

bgridToCell(bgridArray: number[]): {
  lat: number;
  lon: number;
  bounds: [[number, number], [number, number]];
}
ParameterTypeDescription
bgridArraynumber[]Array of grid indices (1–2048)

Returns: Object with lat (center latitude), lon (center longitude), and bounds ([[minLat, minLon], [maxLat, maxLon]]).


getGridCells(level, parentGrid?, maxLevel?)

Generates all grid cells at a specific hierarchical level.

getGridCells(
  level: number,
  parentGrid?: number[],
  maxLevel?: number
): Array<{ index: number; grid: number[]; center: { lat: number; lon: number }; bounds: [[number, number], [number, number]] }>
ParameterTypeDefaultDescription
levelnumberTarget level (1+)
parentGridnumber[][]Parent grid path for sub-queries
maxLevelnumber4Maximum level to generate

Returns: Array of cell objects, each containing index, grid, center, and bounds.


loadLanguage(langCode, options?)

Asynchronously loads a BIP39 wordlist for the specified language.

loadLanguage(langCode: string, options?: { basePath?: string }): Promise<string[]>
ParameterTypeDescription
langCodestringLanguage code: en, es, fr, pt, or zh
options.basePathstringCustom path to wordlist directory (optional)

Returns: Promise resolving to an array of 2048 words.


loadLanguages(langs?, options?)

Loads multiple wordlists in parallel.

loadLanguages(
  langs?: string[],
  options?: { basePath?: string }
): Promise<Record<string, string[]>>
ParameterTypeDefaultDescription
langsstring[]All supportedLanguage codes to load
options.basePathstringPackage defaultCustom wordlist directory

Returns: Promise resolving to a map of language code → word array.


numberToWord(number, words)

Converts a grid index to its corresponding BIP39 word.

numberToWord(number: number, words: string[]): string | null
ParameterTypeDescription
numbernumberGrid index (1–2048)
wordsstring[]Word array from loadLanguage

Returns: Word string, or null if out of range.


wordToNumber(word, words)

Converts a BIP39 word back to its grid index.

wordToNumber(word: string, words: string[]): number | null
ParameterTypeDescription
wordstringBIP39 word (case-insensitive)
wordsstring[]Word array from loadLanguage

Returns: Grid index (1–2048), or null if not found.


gridToDisplay(gridArray, options?)

Formats a grid array as a display string.

gridToDisplay(
  gridArray: number[],
  options?: { mode?: 'numbers' | 'words'; words?: string[] }
): string
ParameterTypeDefaultDescription
gridArraynumber[]Array of grid indices
options.mode'numbers' | 'words''numbers'Output format
options.wordsstring[]Required when mode is 'words'

Returns: Comma-separated string of numbers or words.

BIP39 Word Support

The library supports 5 languages for BIP39 word encoding:

en, es, fr, pt, zh

Word lists are loaded asynchronously via loadLanguage() or loadLanguages(), keeping the core bundle small.

Resources