首页 > 解决方案 > d3-geo:在多个几何图形中查找质心

问题描述

我正在使用react-simple-maps在美国地图上显示一些数据,我需要按一些标准对州进行分组。每个组都应该有自己的标记。我有每个州的地理位置,所以我需要以某种方式将每个州的坐标合并为一个并找到质心。

我不知道该怎么做。目前,我只取组中每个状态的边界(d3-geo:geoBounds)并通过从左上右下的每个边界取最小最大值来计算中心,然后找到这个大区域的中心。

let geosBounds = geos.filter(g => !excludeZones.includes(g.properties.code)).map(g => geoBounds(g))
if (geosBounds.length === 0 && geos.some(g => excludeZones.includes(g.properties.code)) && geos.length === 1) {
  return separateZoneCenters[geos[0].properties.code]
}
const totalArea = geosBounds.reduce((acc, [[x0, y0],[x1, y1]]) => ({
  x0: acc.hasOwnProperty('x0') ? Math.min(acc.x0, x0) : x0,
  x1: acc.hasOwnProperty('x1') ? Math.max(acc.x1, x1) : x1,
  y0: acc.hasOwnProperty('y0') ? Math.min(acc.y0, y0) : y0,
  y1: acc.hasOwnProperty('y1') ? Math.max(acc.y1, y1) : y1,
}), {})
return [
  (totalArea.x1 +  totalArea.x0)  / 2,
  (totalArea.y1 +  totalArea.y0) / 2
];

所以我最后得到了这样的东西:

结果示例

您能否建议我如何将地理合并为一个并找到合适的质心以在组内放置标记?

标签: reactjsd3.js

解决方案


所以,我找到了一种使用 topojson 的解决方案:

const merged = topojson.merge(states, states.objects.states.geometries.filter(geo => group.states.includes(geo.properties.code)))
const centroid = geoCentroid(merged)
return {
  coordinates: centroid,
}

现在的样子

它看起来不错!但也许还有其他解决方案?


推荐阅读