R 如何将 MultiLineString GeoJson 文件转换为具有 long 和 lat 列的数据框?

R How to convert MultiLineString GeoJson file to dataframe with long and lat columns?

我有一个从 gqig gis 软件导出的 MultiLineString Geogeson 文件。 一个小例子:

{
"type": "FeatureCollection",
"name": "route1",
 "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" 
 } },
 "features": [
 { "type": "Feature", "properties": { "FID": 0 }, "geometry": { "type": 
 "MultiLineString", "coordinates": [ [ [ 1936131.287994222715497, 
 -4335318.772792792879045 ], [ -2633407.770391199737787, 
  1763382.609922708477825 ], [ -2922369.195528693497181, 
  4600947.908943663351238 ], [ -1640888.092745035886765, 
  5275789.498084637336433 ], [ -361201.781421858817339, 5970373.793290910311043 
  ], [ -361201.781421858817339, 5970373.793290910311043 ] ] ] 
 } }
]
}

如何在具有长列和纬度列的数据帧绑定节点中转换它? 预期结果:

node    long                    lat 
1   1936131.287994222715497    -4335318.772792792879045 
2   -2633407.770391199737787    1763382.609922708477825 

我尝试过的(创建列表):

  route1 <- jsonlite::fromJSON(readr::read_file("routes/route1.geojson"))

如果您使用 str(route1) 检查获得的列表的结构,您可以看到数据存储在一个数组中,您可以提取它。

a <- route1$features$geometry$coordinates[[1]]
a

# , , 1
# 
#         [,1]     [,2]     [,3]     [,4]      [,5]      [,6]
# [1,] 1936131 -2633408 -2922369 -1640888 -361201.8 -361201.8
# 
# , , 2
# 
#          [,1]    [,2]    [,3]    [,4]    [,5]    [,6]
# [1,] -4335319 1763383 4600948 5275789 5970374 5970374

现在,只需 cbind() 即可获得您想要的。

cbind(a[, , 1], a[, , 2])
#            [,1]     [,2]
# [1,]  1936131.3 -4335319
# [2,] -2633407.8  1763383
# [3,] -2922369.2  4600948
# [4,] -1640888.1  5275789
# [5,]  -361201.8  5970374
# [6,]  -361201.8  5970374

或作为数据框:

d <- data.frame(long=a[, , 1], lat=a[, , 2])
d <- cbind(node=rownames(d), d)
d
#   node       long      lat
# 1    1  1936131.3 -4335319
# 2    2 -2633407.8  1763383
# 3    3 -2922369.2  4600948
# 4    4 -1640888.1  5275789
# 5    5  -361201.8  5970374
# 6    6  -361201.8  5970374

library(sf) 可以读取 GeoJSON。这将为您提供一个 sf 对象。如果你想要坐标,你可以使用 st_coordinates() 函数。

library(sf)

sf <- sf::st_read( geo, quiet = T )
df <- as.data.frame( sf::st_coordinates( sf ) )

#            X        Y L1 L2
# 1  1936131.3 -4335319  1  1
# 2 -2633407.8  1763383  1  1
# 3 -2922369.2  4600948  1  1
# 4 -1640888.1  5275789  1  1
# 5  -361201.8  5970374  1  1
# 6  -361201.8  5970374  1  1

这个额外的 L1L2 列告诉您每个坐标对属于 MULTILINESTRING 中的哪个线串。