Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Efficiently find whether two GeoJSON features overlap?

I need to build a JavaScript function which takes two GeoJSON features as input: Feature A will be a Polygon or Circle; feature B will be a Point, Polygon, Circle or Ellipse.

The function should return, as quickly and efficiently as possible, whether B "touches" A in any way (whether they overlap, whether one is contained within the other, e.g.)

Extreme precision is not important (i.e. I don't care about issues arising from, say, the curvature of the Earth); I also don't need to know any details about how the two features touch one another, just a boolean TRUE or FALSE as to whether or not they do.

If there's a good solution that requires a module, that's perfectly fine -- the only thing that's important is that the actual function is as fast as reasonably possible. E.g. it looks like Turf can do this, but would require executing a few separate functions (intersect, contains, etc.) some of which are overly heavy.

like image 647
DanM Avatar asked Sep 16 '25 00:09

DanM


1 Answers

Fortunately there's a JavaScript port of JTS (Java Topology Suite) - library of spatial predicates and functions for processing geometry conforming to the Simple Features Specification (a standard from the Open Geospatial Consortium)

Its name is JSTS (GeoJSON support included)

https://github.com/bjornharrtell/jsts

  • Typical examples:

Intersection of A and B

var intersection = a.intersection(b)

Difference of A and B

var difference = a.difference(b)

Union of A and B

var union = a.union(b)

Check the test suite for all the use cases including Point in Polygon tests https://github.com/bjornharrtell/jsts/tree/master/test

Also, visual example integrated with Openlayers (with source code): https://openlayers.org/en/master/examples/jsts.html

EDIT 1:

In case you want just one function something like this will do:

var intersection = (a.intersection(b) !== null) ? true : false;
like image 188
LuisTavares Avatar answered Sep 17 '25 16:09

LuisTavares