Node.js/Javascript library to test if point is in geojson multipolygon

4k views Asked by At

Is there some library for node.js or javascript in general that provides a function to check if a coordinate is in a geojson multipolygon?

I'm trying to create a small HTTP API that tells me which multipolygons (representing countries, counties, cities, etc.) contain a given coordinate.

I thought that I'll hold a list of all multipolygons & their bounding-box in memory and then first check for each polygon if its bounding box cointains the coordinate. If yes, then it'll check if the coordinate is in the multipolygon itself.

I know there's a library called "clipper" that got ported to javascript, but it seems that the library does not provide a simple "pointInPolygon" function, even if the library itself is very powerful.. Is it still possible with this library?

Additionally, I've found another library called "geojson-js-utils" but it does not seem to support multipolygons (at least it's not mentioned there)

I've found some other libraries that can check if a point is in a polygon, but I don't know how to use them to check if a point is in a multipolygon.

Any hints?

1

There are 1 answers

1
Timo Kähkönen On

In newest Clipper there is an efficient PointInPolygon function. It uses algorithm The Point in Polygon Problem for Arbitrary Polygons by Hormann & Agathos.

The documentation of Javascript Clipper's PointInPolygon function says:


ClipperLib.Clipper.PointInPolygon()

Number PointInPolygon(IntPoint pt, Path poly)

Returns 0 if false, -1 if pt is on poly and +1 if pt is in poly.

Usage:

var poly = [{X:10,Y:10},{X:110,Y:10},{X:110,Y:110},{X:10,Y:110}];
var pt = new ClipperLib.IntPoint(50,50);
var inpoly = ClipperLib.Clipper.PointInPolygon(pt, poly);
// inpoly is 1, which means that pt is in polygon

To test multipolygon, you can traverse subpolygons and check them using PointInPolygon.