### Install Flatbush using NPM and ES Modules Source: https://github.com/mourner/flatbush/blob/main/README.md Provides instructions on how to install the Flatbush library using NPM and import it as an ES module in your JavaScript project. ```bash npm install flatbush ``` ```javascript import Flatbush from 'flatbush'; ``` -------------------------------- ### JavaScript: Perform Bounding Box Queries with Flatbush Source: https://context7.com/mourner/flatbush/llms.txt Demonstrates how to use Flatbush's `search` method to find items within a specified bounding box. It includes examples of basic searches and filtered searches using a callback function. The optional filter function can be used to refine results or perform actions on intersecting items without adding them to the returned array. ```javascript import Flatbush from 'flatbush'; // Create sample dataset of map features const features = [ { name: 'Restaurant', category: 'food', minX: 10, minY: 10, maxX: 12, maxY: 12 }, { name: 'Coffee Shop', category: 'food', minX: 15, minY: 8, maxX: 17, maxY: 10 }, { name: 'Gas Station', category: 'service', minX: 25, minY: 25, maxX: 28, maxY: 28 }, { name: 'Supermarket', category: 'food', minX: 30, minY: 5, maxX: 35, maxY: 10 }, { name: 'Bank', category: 'service', minX: 8, minY: 20, maxX: 12, maxY: 24 }, { name: 'Pharmacy', category: 'health', minX: 20, minY: 15, maxX: 23, maxY: 18 }, ]; const index = new Flatbush(features.length); features.forEach(f => index.add(f.minX, f.minY, f.maxX, f.maxY)); index.finish(); // Basic search: find all features in viewport const viewport = { minX: 5, minY: 5, maxX: 20, maxY: 20 }; const visibleIds = index.search(viewport.minX, viewport.minY, viewport.maxX, viewport.maxY); console.log('Visible features:', visibleIds.map(i => features[i].name)); // Output: Visible features: ['Restaurant', 'Coffee Shop', 'Pharmacy'] // Filtered search: find only food establishments in viewport const foodIds = index.search(5, 5, 20, 20, (i) => features[i].category === 'food'); console.log('Food places:', foodIds.map(i => features[i].name)); // Output: Food places: ['Restaurant', 'Coffee Shop'] // Using filter callback for side effects (e.g., rendering) const rendered = []; index.search(0, 0, 40, 30, (i, x0, y0, x1, y1) => { rendered.push({ name: features[i].name, bounds: { x0, y0, x1, y1 } }); return false; // Don't include in returned array }); console.log('Rendered items:', rendered.length); // Output: Rendered items: 6 ``` -------------------------------- ### Web Worker Integration: Transferring Flatbush Index Between Threads Source: https://context7.com/mourner/flatbush/llms.txt This example shows how to create a Flatbush spatial index on the main thread, transfer its ArrayBuffer data to a Web Worker using postMessage with transferable objects, and then reconstruct and use the index within the worker for spatial queries. The main thread initiates the process by creating the index and sending it, while the worker listens for the index data and search requests, returning results. ```javascript // === main.js === import Flatbush from 'flatbush'; // Create a large index on the main thread const features = []; for (let i = 0; i < 100000; i++) { features.push({ id: i, minX: Math.random() * 1000, minY: Math.random() * 1000, maxX: 0, maxY: 0 }); features[i].maxX = features[i].minX + Math.random() * 10; features[i].maxY = features[i].minY + Math.random() * 10; } const index = new Flatbush(features.length); features.forEach(f => index.add(f.minX, f.minY, f.maxX, f.maxY)); index.finish(); console.log('Index created, size:', index.data.byteLength, 'bytes'); // Transfer to worker (zero-copy, transfers ownership) const worker = new Worker('worker.js', { type: 'module' }); worker.postMessage({ type: 'index', data: index.data }, [index.data]); // Note: index.data is now detached and unusable on main thread // console.log(index.data.byteLength); // Would throw error // Receive search results from worker worker.onmessage = (e) => { if (e.data.type === 'results') { console.log('Found', e.data.ids.length, 'items in viewport'); } }; // Request a search worker.postMessage({ type: 'search', bounds: { minX: 100, minY: 100, maxX: 200, maxY: 200 }}); ``` ```javascript // === worker.js === import Flatbush from 'flatbush'; let index = null; self.onmessage = (e) => { if (e.data.type === 'index') { // Reconstruct index from transferred buffer index = Flatbush.from(e.data.data); console.log('Worker: Index reconstructed with', index.numItems, 'items'); } if (e.data.type === 'search' && index) { const { minX, minY, maxX, maxY } = e.data.bounds; const ids = index.search(minX, minY, maxX, maxY); self.postMessage({ type: 'results', ids }); } }; ``` -------------------------------- ### Initialize and Index Rectangles with Flatbush Source: https://github.com/mourner/flatbush/blob/main/README.md Demonstrates how to initialize a Flatbush index with a specified number of items, add rectangles to it, and then perform the indexing operation. This is the first step before performing any spatial queries. ```javascript const index = new Flatbush(1000); for (const p of items) { index.add(p.minX, p.minY, p.maxX, p.maxY); } index.finish(); ``` -------------------------------- ### Use Flatbush Browser Bundle with Global Variable Source: https://github.com/mourner/flatbush/blob/main/README.md Demonstrates how to include the Flatbush browser bundle via a CDN, making the `Flatbush` constructor available as a global variable. ```html ``` -------------------------------- ### Initialize Flatbush Index Source: https://context7.com/mourner/flatbush/llms.txt Demonstrates how to instantiate the Flatbush class with different configurations, including custom node sizes, typed arrays for coordinate storage, and shared memory buffers for multi-threaded environments. ```javascript import Flatbush from 'flatbush'; // Basic initialization for 1000 items const basicIndex = new Flatbush(1000); // Optimized for integer coordinates with larger node size const intIndex = new Flatbush(50000, 32, Int32Array); // Shared memory for multi-threaded access via Web Workers const sharedIndex = new Flatbush(10000, 16, Float64Array, SharedArrayBuffer); // Example: Create index with custom configuration const index = new Flatbush(5, 16, Float64Array); console.log(index.numItems); // 5 console.log(index.nodeSize); // 16 ``` -------------------------------- ### Use Flatbush via CDN with ES Modules Source: https://github.com/mourner/flatbush/blob/main/README.md Shows how to use Flatbush directly in the browser by including it via a CDN link as an ES module. ```html ``` -------------------------------- ### Flatbush Constructor Options Source: https://github.com/mourner/flatbush/blob/main/README.md Explains the parameters for the Flatbush constructor, including `numItems`, `nodeSize`, `ArrayType`, and `ArrayBufferType`, and their impact on performance and memory usage. ```javascript // Default constructor: new Flatbush(1000); // With custom options: new Flatbush(1000, 32, Float32Array, SharedArrayBuffer); ``` -------------------------------- ### Finalize and Build Index Source: https://context7.com/mourner/flatbush/llms.txt Explains the necessity of calling the finish() method after adding all items to build the Hilbert R-tree. This step is required before any search operations can be performed. ```javascript import Flatbush from 'flatbush'; // Sample dataset of city blocks const cityBlocks = [ { id: 'A1', minX: 0, minY: 0, maxX: 100, maxY: 100 }, { id: 'A2', minX: 100, minY: 0, maxX: 200, maxY: 100 }, { id: 'B1', minX: 0, minY: 100, maxX: 100, maxY: 200 }, { id: 'B2', minX: 100, minY: 100, maxX: 200, maxY: 200 }, ]; const index = new Flatbush(cityBlocks.length); // Add all items for (const block of cityBlocks) { index.add(block.minX, block.minY, block.maxX, block.maxY); } // Build the index - REQUIRED before any search operations index.finish(); // Now queries will work const results = index.search(50, 50, 150, 150); console.log('Found blocks:', results.map(i => cityBlocks[i].id)); // Error example: trying to finish with wrong item count try { const badIndex = new Flatbush(10); badIndex.add(0, 0, 1, 1); // Only added 1 item, expected 10 badIndex.finish(); // Throws: "Added 1 items when expected 10." } catch (e) { console.error(e.message); } ``` -------------------------------- ### Perform K-Nearest Neighbors Query with Flatbush Source: https://github.com/mourner/flatbush/blob/main/README.md Illustrates how to find the k-nearest neighbors for a given point using the Flatbush index. This is useful for proximity-based searches. ```javascript const neighborIds = index.neighbors(x, y, 5); ``` -------------------------------- ### Recreate Flatbush Index from Buffer Source: https://github.com/mourner/flatbush/blob/main/README.md The from method allows for the reconstruction of a Flatbush index from a raw ArrayBuffer or SharedArrayBuffer. This is essential for sharing indices across web workers or persisting them to disk. ```javascript const index = Flatbush.from(data); ``` -------------------------------- ### Perform Bounding Box Query with Flatbush Source: https://github.com/mourner/flatbush/blob/main/README.md Shows how to query the Flatbush index for items that intersect or touch a given bounding box. The result is an array of indices that can be used to retrieve the original items. ```javascript const found = index.search(minX, minY, maxX, maxY).map((i) => items[i]); // Example with a filter function: const ids = index.search(10, 10, 20, 20, (i) => items[i].foo === 'bar'); // Example with result handling in the callback: index.search(10, 10, 20, 20, (i, x0, y0, x1, y1) => { console.log(`Item found: ${items[i]}, bbox: ${x0} ${y0} ${x1} ${y1}`); }); ``` -------------------------------- ### Transfer and Reconstruct Flatbush Index Source: https://github.com/mourner/flatbush/blob/main/README.md Demonstrates how to transfer the Flatbush index data (as an ArrayBuffer) between threads using `postMessage` and how to reconstruct the index from this data in another context using `Flatbush.from()`. ```javascript // To transfer: postMessage(index.data, [index.data]); // To reconstruct: const index = Flatbush.from(e.data); ``` -------------------------------- ### JavaScript: Perform K-Nearest Neighbors Queries with Flatbush Source: https://context7.com/mourner/flatbush/llms.txt Illustrates the use of Flatbush's `neighbors` method for K-Nearest Neighbors (KNN) searches. This method finds the closest items to a given point (x, y), with options to limit the number of results (`maxResults`) or the maximum search distance (`maxDistance`). An optional `filterFn` can be provided to exclude specific candidates during the search. ```javascript import Flatbush from 'flatbush'; // Create dataset of delivery locations const locations = [ { name: 'Customer A', x: 10, y: 10 }, { name: 'Customer B', x: 25, y: 30 }, { name: 'Customer C', x: 5, y: 45 }, { name: 'Customer D', x: 40, y: 20 }, { name: 'Customer E', x: 15, y: 25 }, { name: 'Customer F', x: 50, y: 50 }, { name: 'Customer G', x: 35, y: 10 }, { name: 'Customer H', x: 20, y: 40 }, ]; const index = new Flatbush(locations.length); locations.forEach(loc => index.add(loc.x, loc.y)); // Points only index.finish(); // Delivery truck at position (20, 20) const truckX = 20, truckY = 20; // Find 3 nearest customers const nearest3 = index.neighbors(truckX, truckY, 3); console.log('3 nearest customers:', nearest3.map(i => locations[i].name)); // Output: 3 nearest customers: ['Customer E', 'Customer A', 'Customer B'] // Find all customers within distance of 20 units const nearby = index.neighbors(truckX, truckY, Infinity, 20); console.log('Customers within 20 units:', nearby.map(i => locations[i].name)); // Output: Customers within 20 units: ['Customer E', 'Customer A', 'Customer B', 'Customer D', 'Customer G'] // Find 5 nearest customers, but only even-indexed ones (simulating priority filter) const filteredNearest = index.neighbors(truckX, truckY, 5, Infinity, i => i % 2 === 0); console.log('Filtered nearest:', filteredNearest.map(i => locations[i].name)); // Output: Filtered nearest: ['Customer A', 'Customer C', 'Customer E', 'Customer G'] // Combine maxResults and maxDistance const limited = index.neighbors(truckX, truckY, 2, 15); console.log('Max 2 within 15 units:', limited.map(i => locations[i].name)); // Output: Max 2 within 15 units: ['Customer E', 'Customer A'] ``` -------------------------------- ### Flatbush.from(data, byteOffset) Source: https://context7.com/mourner/flatbush/llms.txt Reconstructs a Flatbush index from an ArrayBuffer or SharedArrayBuffer, enabling serialization and transfer between threads. ```APIDOC ## Static Method: Flatbush.from(data, byteOffset) ### Description Recreates a Flatbush index from raw ArrayBuffer or SharedArrayBuffer data. This is essential for loading previously saved indices from files or transferring indices between Web Workers. ### Parameters #### Arguments - **data** (ArrayBuffer | SharedArrayBuffer) - Required - The buffer containing the serialized index. - **byteOffset** (number) - Optional - The offset in the buffer where the index data begins. Must be 8-byte aligned. ### Request Example const reconstructed = Flatbush.from(buffer); ### Response - **Flatbush** (Object) - Returns a new Flatbush instance populated with the data from the buffer. ``` -------------------------------- ### Access Flatbush Index Properties Source: https://context7.com/mourner/flatbush/llms.txt Explains how to access various properties of a Flatbush index instance, including the raw data buffer (`data`), bounding box coordinates (`minX`, `minY`, `maxX`, `maxY`), the number of items (`numItems`), node size (`nodeSize`), and internal array types (`ArrayType`, `IndexArrayType`). ```javascript import Flatbush from 'flatbush'; // Create index with various rectangle sizes const index = new Flatbush(5, 16, Float64Array); index.add(-100, -50, 0, 0); // Southwest quadrant index.add(0, 0, 100, 50); // Northeast quadrant index.add(-25, -25, 25, 25); // Center index.add(80, 40, 120, 80); // Far northeast index.add(-150, 60, -80, 100); // Northwest outlier index.finish(); // Access index properties console.log('Number of items:', index.numItems); // 5 console.log('Node size:', index.nodeSize); // 16 console.log('Array type:', index.ArrayType.name); // Float64Array console.log('Index array type:', index.IndexArrayType.name); // Uint16Array // Bounding box of entire dataset console.log('Dataset bounds:'); console.log(` X: ${index.minX} to ${index.maxX}`); // X: -150 to 120 console.log(` Y: ${index.minY} to ${index.maxY}`); // Y: -50 to 100 // Use data buffer for serialization const buffer = index.data; console.log('Index size:', buffer.byteLength, 'bytes'); // 408 bytes console.log('Buffer type:', buffer.constructor.name); // ArrayBuffer // Check if using SharedArrayBuffer (for multi-threaded scenarios) const sharedIndex = new Flatbush(100, 16, Float64Array, SharedArrayBuffer); console.log('Is shared:', sharedIndex.data instanceof SharedArrayBuffer); // true ``` -------------------------------- ### Add Rectangle to Flatbush Index Source: https://github.com/mourner/flatbush/blob/main/README.md Details the `index.add()` method for adding rectangles to the Flatbush index. It accepts `minX`, `minY`, and optionally `maxX`, `maxY`. If `maxX` and `maxY` are omitted, a point is added. ```javascript // Add a rectangle index.add(10, 20, 30, 40); // Add a point index.add(5, 5); ``` -------------------------------- ### Add Items to Spatial Index Source: https://context7.com/mourner/flatbush/llms.txt Shows how to add rectangles and points to the index. The method returns an incremental index ID used for mapping results back to original data objects. ```javascript import Flatbush from 'flatbush'; // Create index for geographic features const index = new Flatbush(5); // Add rectangles (buildings, regions, etc.) const building1 = index.add(10.5, 20.3, 15.2, 25.8); // Returns 0 const building2 = index.add(30.0, 40.0, 35.5, 45.5); // Returns 1 const building3 = index.add(50.0, 10.0, 55.0, 15.0); // Returns 2 // Add points (just provide minX, minY) const point1 = index.add(25.0, 30.0); // Returns 3, stored as (25, 30, 25, 30) const point2 = index.add(60.0, 60.0); // Returns 4 // Store your actual data in a parallel array using returned indices const features = []; features[building1] = { name: 'Office Building', type: 'commercial' }; features[building2] = { name: 'Shopping Mall', type: 'retail' }; features[building3] = { name: 'Warehouse', type: 'industrial' }; features[point1] = { name: 'Bus Stop', type: 'transit' }; features[point2] = { name: 'Park Bench', type: 'amenity' }; // Must call finish() before querying index.finish(); console.log(`Index bounds: (${index.minX}, ${index.minY}) to (${index.maxX}, ${index.maxY})`); ``` -------------------------------- ### Index Properties Source: https://context7.com/mourner/flatbush/llms.txt Accessing internal properties of a Flatbush index instance for metadata and serialization. ```APIDOC ## Instance Properties ### Description Flatbush instances expose several properties for inspecting the index state and performing serialization. ### Properties - **data** (ArrayBuffer) - The binary buffer containing the entire index. - **minX, minY, maxX, maxY** (number) - The bounding box of all indexed items. - **numItems** (number) - The total count of stored items. - **nodeSize** (number) - The tree node size. - **ArrayType** (TypedArray) - The internal storage type used for coordinates. - **IndexArrayType** (TypedArray) - The internal storage type used for indices. ### Example console.log('Number of items:', index.numItems); console.log('Dataset bounds:', index.minX, index.maxX, index.minY, index.maxY); ``` -------------------------------- ### Perform K-Nearest Neighbor Search in Flatbush Source: https://github.com/mourner/flatbush/blob/main/README.md The neighbors method retrieves item indices ordered by distance from a specified coordinate. It supports optional parameters for result limits, maximum distance, and a custom filter function. ```javascript const ids = index.neighbors(10, 10, 5); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.