Skip to content

Instantly share code, notes, and snippets.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@Stophface
Stophface / fastUnion.js
Last active April 17, 2023 11:49
Fast union of geometries in JavaScript using Turf.JS and RBush
// Turf union can be very slow
// The part that is slowing down turf.union() is, that the union function has to compare all the coordinates with each other, in order to avoid duplicate coordinates
// We can speed up this process in two ways
// 1) Only compare the coordinates of the polygons that intersect (idea of ChatGPT)
// 2) Pairwise combine the polygons recursively The cost of computing the union of two polygons scales with the number of points in each. So you can reduce the runtime by reducing the number of operations that involve large polygons. (idea of https://stackoverflow.com/a/70010562/3935035)
const findIntersectingPolygons = (geojson) => {
const allPolygons = turf.getCoords(geojson);
const bboxes = allPolygons.map((coords, index) => {
const polygon = turf.polygon(coords);
{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[102,2],[103,2],[103,3],[102,3],[102,2]]],[[[100,0],[101,0],[101,1],[100,1],[100,0]],[[100.2,0.2],[100.2,0.8],[100.8,0.8],[100.8,0.2],[100.2,0.2]]],[[[100.3,0.3],[100.7,0.3],[100.7,0.7],[100.3,0.7],[100.3,0.3]],[[100.4305160192801,0.67817296142852],[100.43926588878527,0.6777431305923907],[100.44793148784716,0.6764577778174132],[100.45642935778174,0.6743292824257617],[100.46467765559704,0.6713781440787653],[100.47259694234847,0.667632785305691],[100.48011094831709,0.6631292777150927],[100.48714730763562,0.6579109945286341],[100.49363825528266,0.6520281927874464],[100.49952127973005,0.6455375292587178],[100.50473972495757,0.6385015147088778],[100.50924333603814,0.6309879118031904],[100.5129887430422,0.6230690824341719],[100.51593987860606,0.6148212907677792],[100.51806832514795,0.6063239687221135],[100.51935358839506,0.5976589509544159],[100.51978329459449,0.5889096867249723],[100.51935330951578,0.580160