12

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?

Van Coding
  • 24,244
  • 24
  • 88
  • 132

1 Answers1

0

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.

Timo Kähkönen
  • 11,962
  • 9
  • 71
  • 112
  • the thing is that clipper is this: "The Javascript Clipper Library performs clipping and offsetting of both lines and polygons.", but geolocation is another thing, it involves sin cos stuff to take in account the radius of earth. The problem is placed in a sphere instead of a 2d plane, the approach is another one – Julio Marins Jan 15 '16 at 03:13