@allmaps/render
Version:
Render functions for WebGL and image buffers
79 lines (78 loc) • 2.04 kB
JavaScript
import RBush from "rbush";
import inside from "point-in-polygon-hao";
import { computeBbox } from "@allmaps/stdlib";
const DEFAULT_FILTER_INSIDE_POLYGON = true;
class RTree {
rbush = new RBush();
polygonsById = /* @__PURE__ */ new Map();
bboxesById = /* @__PURE__ */ new Map();
itemsById = /* @__PURE__ */ new Map();
addItem(id, polygon) {
this.removeItem(id);
const bbox = computeBbox(polygon);
const item = {
minX: bbox[0],
minY: bbox[1],
maxX: bbox[2],
maxY: bbox[3],
id
};
this.polygonsById.set(id, polygon);
this.bboxesById.set(id, bbox);
this.itemsById.set(id, item);
this.rbush.insert(item);
}
removeItem(id) {
const item = this.itemsById.get(id);
if (item) {
this.rbush.remove(item);
this.polygonsById.delete(id);
this.bboxesById.delete(id);
this.itemsById.delete(id);
}
}
clear() {
this.polygonsById.clear();
this.bboxesById.clear();
this.itemsById.clear();
this.rbush.clear();
}
search(minX, minY, maxX, maxY) {
return this.rbush.search({
minX,
minY,
maxX,
maxY
});
}
getBbox(id) {
return this.bboxesById.get(id);
}
getPolygon(id) {
return this.polygonsById.get(id);
}
searchFromBbox(bbox) {
const [minX, minY, maxX, maxY] = bbox;
return this.search(minX, minY, maxX, maxY).map((item) => item.id);
}
searchFromPoint(point, filterInsidePolygon = DEFAULT_FILTER_INSIDE_POLYGON) {
const [minX, minY, maxX, maxY] = [point[0], point[1], point[0], point[1]];
const rtreeResults = this.search(minX, minY, maxX, maxY);
if (filterInsidePolygon) {
return rtreeResults.filter((item) => {
const polygon = this.polygonsById.get(item.id);
if (polygon) {
return inside(point, polygon);
} else {
return false;
}
}).map((item) => item.id);
} else {
return rtreeResults.map((item) => item.id);
}
}
}
export {
RTree
};
//# sourceMappingURL=RTree.js.map