rbush

repository·main·Indexed 25 days ago

https://github.com/mourner/rbush

A high-performance JavaScript library for 2D spatial indexing of points and rectangles based on an optimized R-tree data structure. It supports bulk loading and insertion algorithms, spatial search, collision detection, and JSON serialization. Version 4.0.1.

Tokens
1.6K
Snippets
7
Records
16
Agent score
33%

What's inside rbush

  1. Install RBush via NPM or CDN

    main

    NPM

    Install with NPM:

    npm install rbush

    Then import as a module:

    import RBush from 'rbush';

    Browser (ESM)

    Use directly in the browser via jsDelivr:

    <script type="module">
        import RBush from 'https://cdn.jsdelivr.net/npm/rbush/+esm';
    </script>

    Browser (Global Variable)

    Use the browser bundle which provides an RBush global variable:

    <script src="https://cdn.jsdelivr.net/npm/rbush"></script>
    npm install rbush
  2. Bulk-insert data for better performance

    main

    Use tree.load() to bulk-insert an array of items. Bulk insertion is typically 2-3x faster than individual insertions.

    Note on performance:

    • If loading into an empty tree, subsequent query performance improves by ~20-30%.
    • If loading into an existing tree, RBush builds a separate tree for the new data and inserts it into the larger tree. This is efficient for clustered data but can degrade query performance if the new data is scattered.
    tree.load([item1, item2, ...]);
  3. Export and import tree data as JSON

    main

    You can serialize the tree to JSON for storage or to transfer data between a server (Node.js) and a client (browser).

    Important: The nodeSize option passed to the constructor must be identical in both the exporting and importing trees for the data to be valid.

    // export data as JSON object
    const treeData = tree.toJSON();
    
    // import previously exported data
    // Note: nodeSize must match the original tree
    const tree = rbush(9).fromJSON(treeData);
  4. Search and check for collisions

    main

    Find all items that intersect a given bounding box. The search box must be in {minX, minY, maxX, maxY} format, regardless of your custom data format.

    const result = tree.search({
        minX: 40,
        minY: 20,
        maxX: 80,
        maxY: 70
    });

    Collision Detection

    Check if any items intersect the given bounding box. Returns true or false.

    const hasCollision = tree.collides({minX: 40, minY: 20, maxX: 80, maxY: 70});

    Get all items

    const allItems = tree.all();
    const result = tree.search({
        minX: 40,
        minY: 20,
        maxX: 80,
        maxY: 70
    });
    
    const collides = tree.collides({minX: 40, minY: 20, maxX: 80, maxY: 70});
    
    const allItems = tree.all();
  5. Add and remove data from the tree

    main

    Insert an item

    Items must follow the default data format (see Data Format) or a custom format.

    tree.insert(item);

    Remove an item

    By default, remove uses object reference. To remove an item using a copy (e.g., from a server), provide a custom equals comparator:

    tree.remove(itemCopy, (a, b) => {
        return a.id === b.id;
    });

    Clear all items

    tree.clear();
    const item = {
        minX: 20,
        minY: 40,
        maxX: 30,
        maxY: 50,
        foo: 'bar'
    };
    tree.insert(item);
    tree.remove(item);
    tree.clear();
  6. Define custom data formats

    main

    By default, RBush expects objects with minX, minY, maxX, and maxY properties. You can customize how data is read and compared by extending the RBush class and overriding toBBox, compareMinX, and compareMinY.

    class MyRBush extends RBush {
        toBBox([x, y]) { return {minX: x, minY: y, maxX: x, maxY: y}; }
        compareMinX(a, b) { return a.x - b.x; }
        compareMinY(a, b) { return a.y - b.y; }
    }
    const tree = new MyRBush();
    tree.insert([20, 50]); // accepts [x, y] points
  7. Create an RBush tree

    main

    Initialize a new R-tree instance using new RBush().

    You can optionally pass a nodeSize argument to define the maximum number of entries in a tree node. The default is 9.

    • Higher value: Faster insertion, slower search.
    • Lower value: Slower insertion, faster search.
    const tree = new RBush();
    // or with custom node size
    const tree = new RBush(16);
  8. Check for collisions with a bounding box

    main
    Use collides(bbox) to quickly determine if any item in the tree intersects with the provided bounding box. This is more efficient than search() if you only need a boolean result.
  9. Initialize RBush

    main
    Create a new RBush instance to manage a spatial index of rectangles. You can optionally specify maxEntries, which determines the maximum number of items in a node. The default is 9. The library automatically calculates a minimum node fill of 40% of maxEntries for optimal performance.
  10. Insert items into RBush

    main
    Add items to the spatial index using the insert(item) method. Items must be objects that represent a bounding box. By default, the library expects items to have minX, minY, maxX, and maxY properties. You can override how bounding boxes are extracted by providing a custom toBBox(item) implementation.
  11. Customize bounding box extraction with toBBox

    main
    By default, RBush expects items to have minX, minY, maxX, and maxY properties. You can extend the RBush class and override the toBBox(item) method to support different data formats (e.g., GeoJSON features or objects with different property names).