retrieve countyid from coordinates

Hi,
I am calibrating a function getCountyId that receives coordinates and features as parameters, it returns levels id from Ecuador.
Here is the code

function getCountyId(features, point) {
const n = features.length
if (!!point) {
for (let i = 0; i < n; i++) {
const coordinates = features[i].geometry.coordinates[0]
if (d3.polygonContains(coordinates, point)) {
return features[i].id
}
}
return NaN
}
}

The function is working around 80% and still has problems with some provinces from Ecuador.
Here is the status of the number of coordinates that the function doesn’t identify.
Map(6) {“ESMERALDAS” => 59, “GUAYAS” => 501, “EL ORO” => 10, “MANABI” => 15, “AZUAY” => 2, “GALAPAGOS” => 1}

Any suggestion would be eternally appreciated.

Notebook is here
Missed in Ecuador

Here’s an approach that seems to solve 99% of the points, by taking into account the multipolygons:

function getCountyId(features, point) {
  // ref https://stackoverflow.com/questions/71272770/using-d3-to-retrieve-a-topojson-u-s-county-from-coordinates
  const n = features.length;
  if (!!point) {
    for (let i = 0; i < n; i++) {
      const geometry = features[i].geometry;
      // treat Polygon as MultiPolygon
      for (const coordinates of geometry.type === "Polygon"
        ? [geometry.coordinates]
        : geometry.coordinates) {
        if (d3.polygonContains(coordinates[0], point)) {
          return features[i].id;
        }
      }
    }
    return NaN;
  }
}

It’s a bit slow, but this is a different question :slight_smile:

Thanks, Philipe