首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R中将SpatialPolygonsDataFrame导出为geojson或topojson

在R中将SpatialPolygonsDataFrame导出为geojson或topojson
EN

Stack Overflow用户
提问于 2020-10-26 21:17:56
回答 1查看 619关注 0票数 0

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

代码语言:javascript
复制
Error in sp::SpatialPolygonsDataFrame(polys, data = input@data) : 
  row.names of data and Polygons IDs do not match

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

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-06 06:18:20

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

代码语言:javascript
复制
library(sf)                                                                                                                               
df_hex = st_as_sf(df_hex)                                                                                                                 
st_write(df_hex, "df_hex.geojson") 

以下是QGIS中的结果:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64537922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档