使用 jq 计算 geoJSON 多边形的重心

Computing the center of gravity of a geoJSON Polygon using jq

我有一个由 geoJSON 文件中的多边形描述的城市列表。

我想获取多边形内点的样本。

基础数学说重心在多边形内部,将所有经度和所有纬度相加然后除以点数就足够了。

Full file to process(可视化在 GitHub 上可用)

{
  "type": "FeatureCollection",
  "features": [
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [[[2.41101, 48.72605], [2.41554, 48.72656], [2.41718, 48.72791], [2.4211, 48.72953], [2.42603, 48.72824], [2.42756, 48.72865], [2.42922, 48.72723], [2.43133, 48.72646], [2.43404, 48.72665], [2.43513, 48.72409], [2.42554, 48.7227], [2.42072, 48.72105], [2.41426, 48.71782], [2.41327, 48.71869], [2.41582, 48.72086], [2.41238, 48.72193], [2.41136, 48.72325], [2.41101, 48.72605]]]
    },
    "properties": {
      "code": "94001",
      "nom": "Ablon-sur-Seine"
    }
  },
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [[[2.41959, 48.81691], [2.4159, 48.81633], [2.40936, 48.81667], [2.40787, 48.81746
    },
    "properties": {
      "code": "94018",
      "nom": "Charenton-le-Pont"
    }
  },
  ...
  ]
}

我已经有了计算多边形顶点长度的命令。

$ curl -s https://raw.githubusercontent.com/gregoiredavid/france-geojson/master/departements/94-val-de-marne/communes-94-val-de-marne.geojson \
> | jq '.features[0].geometry.coordinates[0][][0]' \
> | jq -s 'add/length'
2.4206944444444445

https://unix.stackexchange.com/questions/13731/

使用jq和简单的bash命令,我如何计算经度和和纬度之和,并在另一个properties字段中重新注入重心geoJSON 文件?

谢谢。

警告

多边形的 "center of gravity" 通常与根据其顶点的 x 和 y 坐标的平均值定义的点不同。参见例如https://math.stackexchange.com/questions/3177/why-doesnt-a-simple-mean-give-the-position-of-a-centroid-in-a-polygon

纬度和经度的平均值

这是一个 jq 过滤器, 通过一次调用 jq 并且没有冗余,计算每个 "feature":

的纬度和经度的平均值
.features[].geometry.coordinates[0]
| [ [.[][0]], [.[][1]] ]
| map(add/length)

使用 -c 命令行选项,这会生成一个数组流,每个 "feature" 对应一个数组。直播开始:

[2.4206944444444445,48.724651111111115]
[2.407614,48.82250133333333]
...

当然还有其他选择,但请注意,不需要使用字符串插值来执行分组,因此通常不需要像您的第一个版本那样tr

所以如果我没理解错的话,你是在尝试获取第一组坐标的平均值,然后更新属性以存储结果。

.features[] |= (
    (.geometry.coordinates[0] | length as $len | reduce .[] as [$x, $y] ([0,0];
        [.[0] + $x, .[1] + $y]
    ) | map(. / $len)) as $barrycenter |
    .properties.barycenter = $barrycenter
)