s2-tools
Version:
A collection of geospatial tools primarily designed for WGS84, Web Mercator, and S2.
78 lines • 2.56 kB
JavaScript
import wasmBase64 from './s2cell.wasm';
import { fromLonLat, toST } from '../geometry/s2/point';
/**
* Generator that builds S2Cells from either lon/lat, S2Point, or face/s/t
*/
export class S2CellGenerator {
instance;
wasmMemory;
tmpString = '';
#finalizationRegistry;
/**
* Creates an instance of S2CellGenerator that manages the wasm memory
*/
constructor() {
const mod = new WebAssembly.Module(base64ToArrayBuffer(wasmBase64));
this.instance = new WebAssembly.Instance(mod, {
env: {},
});
this.#finalizationRegistry = new FinalizationRegistry((id) => {
const freeS2CellId = this.instance.exports.free_s2_cell_id;
freeS2CellId(id);
});
}
/**
* @param lon - longitude
* @param lat - latitude
* @returns - an S2Cell with the appropriate id and functions
*/
fromLonLat(lon, lat) {
return this.fromS2Point(fromLonLat(lon, lat));
}
/**
* @param point - a vector point on the sphere
* @returns - an S2Cell with the appropriate id and functions
*/
fromS2Point(point) {
const [face, s, t] = toST(point);
return this.fromFaceST(face, s, t);
}
/**
* @param face - face on the sphere
* @param s - x position
* @param t - y position
* @returns - an S2Cell with the appropriate id and functions
*/
fromFaceST(face, s, t) {
const fromFaceST = this.instance.exports.from_face_st;
const comparitor = this.instance.exports.compare_s2_cell_id;
const id = fromFaceST(face, s, t);
const cell = {
id,
/**
* @param other - other S2Cell to compare to
* @returns -1 | 0 | 1; -1 if this < other, 0 if this == other, 1 if this > other
*/
compare: (other) => {
return comparitor(id, other.id);
},
};
// Register the id with the finalization registry to ensure it gets freed
this.#finalizationRegistry.register(cell, id);
return cell;
}
}
/**
* pollyfill for string to array buffer
* @param base64 - base64 encoded string
* @returns converted ArrayBuffer of the string data
*/
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++)
bytes[i] = binaryString.charCodeAt(i);
return bytes.buffer;
}
//# sourceMappingURL=s2cell.js.map