25
votes

Is it possible to determine whether a GeoJSON point at a given lat,lon lies within a given GeoJSON polygon using only JavaScript (either through d3, topojson, or any other way)?

For example, I can draw a map showing countries in the UK based on the tutorial here.

I then have a some points which have coordinates but no indication as to which country they lie within.

I would like to display a total point count for each country.

Can I work out which country contains each point in the browser, or do I need to preprocess my point data on the server using PostGIS or similar?

3
@altocumulus - Your comment led me to JavaScript Clipper - looks interesting. Also, it would never have occurred to me that 'point-in-polygon' would be a tag.user5325596
Agreed, that point-in-polygon tag took me completely by suprise ;-) And there are almost 120 questions associated with it. If you come up with a solution to your problem by yourself, please post an answer to this question.altocumulus
You can also take a look at github.com/turfjs/turf, perhaps too big for this simple task.Jonatas Walker
@jonatas_walker Turfjs has a modular ecosystem so you could just use @turfjs/inside via npmjs.com/package/turf-inside or if you don't use npm then find it on githubAndi-lo

3 Answers

17
votes

Seems like d3 has you covered: https://github.com/d3/d3-geo#geoContains

d3.geoContains(object, point)

Returns true if and only if the specified GeoJSON object contains the specified point, or false if the object does not contain the point. The point must be specified as a two-element array [longitude, latitude] in degrees. For Point and MultiPoint geometries, an exact test is used; for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied.

5
votes

Expanding the @thedude answer's you can also use geojson-lookup if you need to do this check more than once on a given GeoJSON.

0
votes

Turf.js provides a function called boolean-point-in-polygon

For example:

var pt = turf.point([-77, 44]);

var poly = turf.polygon([[
  [-81, 41],
  [-81, 47],
  [-72, 47],
  [-72, 41],
  [-81, 41]
]]);

turf.booleanPointInPolygon(pt, poly);
//= true