Anthony Luzquiños
Anthony Luzquiños

Reputation: 874

How to find point (lat, lng) inside a polygon with h3-js?

I have a polygon created with polyfill, is it possible to know if the point = [lat, lng] is in that polygon (using only h3-js)?

Upvotes: 0

Views: 579

Answers (1)

nrabinowitz
nrabinowitz

Reputation: 55688

Yes, this is possible, though there's simplification involved - polyfill returns cells whose centers fall within the polygon, so you'll have cases at the edges of the polygon where specific points near the edge will be incorrectly included or excluded from the polygon. The tradeoff is that the inclusion check should be much faster than a traditional point-in-poly algorithm, and the code is simpler:

// Create a set of H3 indexes representing the polygon. Using a finer
// value for H3_RES will give you better fidelity to the original 
// polygon, at the cost of more memory usage 
const polygonSet = new Set(h3.polyfill(myPolygon, H3_RES));

// Check whether a given point is in the polygon
function isPointInPoly(point) {
  const h3Index = h3.geoToH3(point.lat, point.lng, H3_RES);
  return polygonSet.has(h3Index);
}

Upvotes: 1

Related Questions