使用 Powershell 从 geojson 获取坐标

Get coordinates from geojson with Powershell

我正在尝试将区域名称和边界从 geojson 导出到 csv。这是我的数据示例:

{
  "type" : "FeatureCollection",
  "features" : [{
     "type":"Feature",
        "properties" : {
           "id"            : "72639",
           "alltags"       : {
              "name:en" : "Area1",
              "admin_level" : "4"}
           },
           "geometry": {"type":"MultiPolygon","coordinates":[[[[36.407,45.071],[36.408,45.072],[36.406,45.071],[36.407,45.071]]],[[[35.082,45.611],[35.084,45.605],[35.082,45.611],[35.082,45.611]]]]}
        },{
     "type":"Feature",
        "properties" : {
           "id"            : "71245",
           "alltags"       : {
              "name:en" : "Area2",
              "admin_level" : "4"}
           },
           "geometry": {"type":"MultiPolygon","coordinates":[[[[27.189,50.625],[29.196,51.607],[27.195,50.561],[27.190,50.624],[27.189,50.625]]]]}
        } ]
}

我想用 'name:en' 和这样的坐标获得输出:

Area1
[[[[36.407,45.071],[36.408,45.072],[36.406,45.071],[36.407,45.071]]],[[[35.082,45.611],[35.084,45.605],[35.082,45.611],[35.082,45.611]]]]
Area2
[[[[27.189,50.625],[29.196,51.607],[27.195,50.561],[27.190,50.624],[27.189,50.625]]]]

我使用以下脚本:

$path = "D:\!map\!test\"
$name_in = "test.GeoJson"
$coords_pattern = '"value":(.*?),"Count"'

$inputjson = Get-Content -Raw -Path $path$name_in | ConvertFrom-Json
Foreach ($feature in $inputjson.features){
   $area_name = $feature.properties.alltags.'name:en'
   $geojson = $feature.geometry
   $coordinates = $geojson.coordinates | ConvertTo-Json -Compress
   $borders = [regex]::match($coordinates, $coords_pattern).Groups[1].Value
   Write-Host $area_name
   Write-Host $borders
}

Area2 一切正常,但 Area1 由 2 组坐标组成,Area1 的输出为 'broken':

Area1
[["36.407 45.071","36.408 45.072","36.406 45.071","36.407 45.071"]]
Area2
[[[27.189,50.625],[29.196,51.607],[27.195,50.561],[27.190,50.624],[27.189,50.625]]]

在实际数据中,区域可能有未知数量的坐标组。如何获得正确的坐标集?

也许使用-replace更简单:

$inputjson = $geo | ConvertFrom-Json
Foreach ($feature in $inputjson.features){
   $area_name = $feature.properties.alltags.'name:en'
   $geojson = $feature.geometry
   $coordinates = ($geojson.coordinates | ConvertTo-Json -Compress -Depth 4) -replace '\{"value":|,"Count":1\}|"', ''
   Write-Host $area_name
   Write-Host $coordinates
}

输出:

Area1
[[[[36.407,45.071],[36.408,45.072],[36.406,45.071],[36.407,45.071]]],[[[35.082,45.611],[35.084,45.605],[35.082,45.611],[35.082,45.611]]]]
Area2
[[[27.189,50.625],[29.196,51.607],[27.195,50.561],[27.190,50.624],[27.189,50.625]]]

我不知道坐标数组的嵌套可以有多深,所以你必须使用 ConvertTo-Json cmdlet 上的 -Depth 参数