Mistake computing district centroids

I have a dataset of earthquakes of my country but it doesn’t have references about where was the epicenter.
So I decided to compute the centroid of each county (called district in Perú) that is located near the shore and then compute which location has the closest distance to the epicenter.
But the centroid function and other close variations are not working with the features i have. Could be something related to the projection?. What am I doing wrong?
Here is the notebook https://observablehq.com/@ccalobeto/peru-earthquakes-1960-2024

districts = {
  const topo = topojson.feature(pe, pe.objects.level4)
  topo.features.forEach(feature => {
    feature.centroid = centroid(feature)
    feature.centroid1 = d3.geoCentroid(feature)
    feature.centroid2 = projection(d3.geoCentroid(feature))
    return feature
  return topo
centroid = (feature) => {
  const geometry = feature.geometry;
  if (geometry.type === "Polygon"){
    return d3.geoCentroid(feature);
  else {
    let largestPolygon = {}, largestArea = 0;
    geometry.coordinates.forEach(coordinates => {
      const polygon = { type: "Polygon", coordinates },
            area = d3.geoArea(polygon);
      if (area > largestArea) {
        largestPolygon = polygon;
        largestArea = area;
    return d3.geoCentroid(largestPolygon);

It seems that your notebook is still private?

It is ok now. Thanks @mootari

any suggestion of what is happening, please

Can you elaborate on what you mean by “not working”? Are you getting an error? Is the computed centroid not in the place you expect? What do you expect or want to happen, and how is what is happening different? If you reduce the problem down to its essence it’ll be easier for us to help you.

I am sorry Mike. The centroids are not in the place I expect.
Here is more detail of what I found

  • The projection I used is d3.geoIdentity().reflectY(true) and there is no problem with this projection since the data points of earthquakes are well displayed.
  • The problem are the centroid computations of each district (level4 in the cartography) with d3.geoCentroid(feature). They throw centroid coordinates in Malasia, but should be in Perú.
  • Just in case I tried projection.invert and throws centroid coordinates in Ecuador.

obs. The Peru’s bounding box is : Lon: [-87.382, -65.624]; lat: [-1.396, -25.701]

Perú Cartography

Try this: Geo: Rewind / Fil | Observable

It will cure polygons that might be defined with the opposite winding order to what geoCentroid expects.

Cool! Thanks @Fil.