【问题标题】:Export SpatialPolygonsDataFrame as geojson or topojson in R在 R 中将 SpatialPolygonsDataFrame 导出为 geojson 或 topojson
【发布时间】:2021-02-08 18:10:10
【问题描述】:

我正在尝试将伦敦地方当局的 geojson 转换为六角制图,其中每个六边形代表一个地方当局。它在 R 中工作,但是当我尝试将生成的 hexgrid 导出为 geojson 或 topojson 时,我收到以下错误:

Error in sp::SpatialPolygonsDataFrame(polys, data = input@data) : 
  row.names of data and Polygons IDs do not match

这是代码。我正在使用geogrid生成网格和geojsonio将生成的数据框导出到geojson或topojson:

library(geogrid)
library(geojsonio) # version 0.9.0

df <- read_polygons(system.file("extdata", "london_LA.json", package = "geogrid"))
# you can get the json file from here: https://github.com/jbaileyh/geogrid/blob/master/inst/extdata/london_LA.json

# Set arguments for plot
par(mfrow = c(2, 3), mar = c(0, 0, 2, 0))

# Hexagonal grid with 6 seeds
for (i in 1:3) {
  grid_hexagon <- calculate_grid(shape = df, learning_rate = 0.05, grid_type = "hexagonal", seed = i)
  plot(grid_hexagon, main = paste("Seed", i, sep = " "))
}

# Square grid
for (i in 1:3) {
  grid_square <- calculate_grid(shape = df, grid_type = "regular", seed = i)
  sp::plot(grid_square, main = paste("Seed", i, sep = " "))
}

# Get a SpatialDataFrame from our desired grid
tmp <- calculate_grid(shape = df, grid_type = "hexagonal", seed = 3)
df_hex <- assign_polygons(df, tmp)

# And export to TopoJSON
topojson_write(df_hex, object_name = "local_authorities", file = "output/london_hex.json")

关于如何解决此问题的任何建议?此外,我有兴趣了解其他方法来生成提供特定输入文件的十六进制地图。

参考:https://github.com/jbaileyh/geogrid

【问题讨论】:

    标签: r sf hexagonal-tiles geojsonio


    【解决方案1】:

    您可以将SpatialPolygonsDataFrame 转换为sf,然后使用st_write 写入GeoJSON 文件:

    library(sf)                                                                                                                               
    df_hex = st_as_sf(df_hex)                                                                                                                 
    st_write(df_hex, "df_hex.geojson") 
    

    这是 QGIS 中的结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 2014-01-13
      • 2013-01-22
      • 2014-08-02
      • 2017-01-20
      • 2015-07-29
      • 1970-01-01
      相关资源
      最近更新 更多