geohash.ts (913B)
1 import { decodeBase32, encodeBase32 } from "geohashing"; 2 import type { GeolocationPoint, LocationPoint } from "./types.js"; 3 4 export const geohash_encode = (opts: { 5 lat: string | number; 6 lng: string | number; 7 }): string => { 8 const lat = typeof opts.lat === "string" ? parseFloat(opts.lat) : opts.lat; 9 const lng = typeof opts.lng === "string" ? parseFloat(opts.lng) : opts.lng; 10 const geohash = encodeBase32(lat, lng); 11 return geohash; 12 }; 13 14 export const geohash_decode = (geohash: string): LocationPoint => { 15 const { lat, lng, error: { lat: lat_err, lng: lng_err } } = decodeBase32(geohash); 16 return { 17 lat, 18 lng, 19 error: { 20 lat: lat_err, 21 lng: lng_err, 22 }, 23 }; 24 }; 25 26 export const location_geohash = (point: GeolocationPoint): string => { 27 const { lat, lng } = point; 28 const res = geohash_encode({ lat, lng }); 29 return res; 30 };