@math.gl/geohash
Version:
Math for the GeoHash DGGS (Discrete Global Grid System)
90 lines (87 loc) • 2.59 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
getGeohashBoundary: () => getGeohashBoundary,
getGeohashBoundaryFlat: () => getGeohashBoundaryFlat,
getGeohashBounds: () => getGeohashBounds,
getGeohashLngLat: () => getGeohashLngLat
});
module.exports = __toCommonJS(src_exports);
// src/geohash.ts
var BASE32_CODES = "0123456789bcdefghjkmnpqrstuvwxyz";
var BASE32_CODES_DICT = {};
for (let i = 0; i < BASE32_CODES.length; i++) {
BASE32_CODES_DICT[BASE32_CODES.charAt(i)] = i;
}
var MIN_LAT = -90;
var MAX_LAT = 90;
var MIN_LON = -180;
var MAX_LON = 180;
function getGeohashLngLat(geohash) {
const [s, w, n, e] = getGeohashBounds(geohash);
return [(e + w) / 2, (n + s) / 2];
}
function getGeohashBoundary(geohash) {
const [s, w, n, e] = getGeohashBounds(geohash);
return [
[e, n],
[e, s],
[w, s],
[w, n],
[e, n]
];
}
function getGeohashBoundaryFlat(geohash) {
const [s, w, n, e] = getGeohashBounds(geohash);
return [e, n, e, s, w, s, w, n, e, n];
}
function getGeohashBounds(geohash) {
let isLon = true;
let maxLat = MAX_LAT;
let minLat = MIN_LAT;
let maxLon = MAX_LON;
let minLon = MIN_LON;
let mid;
let hashValue = 0;
for (let i = 0, l = geohash.length; i < l; i++) {
const code = geohash[i].toLowerCase();
hashValue = BASE32_CODES_DICT[code];
for (let bits = 4; bits >= 0; bits--) {
const bit = hashValue >> bits & 1;
if (isLon) {
mid = (maxLon + minLon) / 2;
if (bit === 1) {
minLon = mid;
} else {
maxLon = mid;
}
} else {
mid = (maxLat + minLat) / 2;
if (bit === 1) {
minLat = mid;
} else {
maxLat = mid;
}
}
isLon = !isLon;
}
}
return [minLat, minLon, maxLat, maxLon];
}