🏠 back to Observable

Find if a given point is inside a Density Contour (and which one)

Hello. First of all, thank you for your attention and sorry for my stupid question:

Given a 2D Point (X, Y) and a set of Density Contours similar to:

https://www.d3-graph-gallery.com/graph/density2d_contour.html

How do I find if this Point is inside any of the generated Contours (and which Contour, if so)?

I’ve tried looping over the ‘MultiPolygon’ objects generated by the d3.contourDensity() function and calculating the Point distance with d3.geoContains() and had no luck since the results were always true.

Also tried using the Closest Point function (https://bl.ocks.org/mbostock/8027637) on the generated SVG Paths.

The success rush lasted a while but testing made me realize that each SVG Path contained multiple Polygons (One SVG Path created for each density level - stupid me).

At the moment I am on the verge of trying to split the ‘MultiPolygon’ objects into individual ‘Polygons’ and seeing where this road would lead me.

I know this is probably a bad decision. There is probably an easier way to solve this.

Could anyone please help me?

Again, sorry for the stupid question. Also sorry for my poor english.

Thanks again

Nailed it after a while.

1 - Ended up splitting into individual polygons and rewriting the ‘Closest Point function’ into a ‘Inside Point function’.
2 - Along a given Path (single Polygon now) I generated two sets of distances at each ‘precision’ step (Path Centroid to Point and Path Centroid to polygon edge).
3 - When the angle of these two distance vectors are the same, if the Centroid-Point distance is bigger than the Centroid-Edge distance, the Point is considered Outside a Polygon. Return false.

Pretty complicated. If anyone has better ideas: please do reply. Gonna drink some beer now. :beer:

1 Like

I can only suppose, but if you are using d3.geoContains, it expects a geojson in WGS84 coordinates (longitude, latitude expressed in degrees), and you probably fed it a geojson in screen coordinates (pixels).

You might be more lucky with https://github.com/d3/d3-polygon#polygonContains, though the syntax is a bit different (so you’ll have to loop in the coordinates of each MultiPolygon of your geojson).