Fast polygon union in javascript

1.5k views Asked by At

I have a large (2.5 MB) geoJSON file with polygons and multi-polygons.

I want to get the union of all of them to plot on a map in the browser.

In python I use shapely.ops.unary_union which takes less than a second

In javascript is use turf.union (docs) which takes almost a minute with the same file...

Is there a way to achieve fast polygon union in javascript? I am trying to avoid doing that on the server side

Python code:

from shapely.ops import unary_union
from shapely.geometry import shape
geoJSON=json.load(open(filename,'rb'))
shapes=[]
for feature in geoJSON['features']:
    shapes.append(shape(feature['geometry']))
union = unary_union(shapes)

Javascript code:

function union(geojson){
    features = geojson.features
    union = turf.union(...features)
}
2

There are 2 answers

2
zingi On

If you need a really fast way to merge polygons on client side then I would recommend to write a polygon-union algorithm in Rust or C++ and compile it to WebAssembly.

You can then import the .wasm file into Javascript and benefit from the speed of WebAssembly.

0
AAS On

This ain't really a solution but found it faster than processing all the features at once

union = features.reduce((accUnion,feature,index)=>index?turf.union(accUnion,feature):feature,null);