r - 如何将 OSM 多边形数据从 PostGIS 导入到 R?

标签 r postgresql postgis spatial ogr

我是使用 R 进行空间分析的新手。使用 this链接 我已经下载了 .osm.pbf 格式的 OSM 数据。然后我用了 osm2pgsql在 PostgreSQL(PostGIS 扩展)中获取数据的工具。现在我的数据库中有几个表,我想访问 R 中的多边形表,然后对多边形矢量数据执行空间分析。我一直在搜索分配但无法在 R 中导入所需的数据。我找到了 this教程与我正在寻找的非常相似,但它是用 Python 编写的。我想使用 R 从 PostGIS 访问多边形数据。

因此,基本上我想了解 R 与 PostGIS 的交互。谁能给我推荐任何关于这个主题的书?由于到目前为止我找不到适用于我的 Windows 10 64 位计算机的博客或教程。

感谢您抽出时间,期待您的建议。

最佳答案

我仍然没有找到使用 R 中可用的 rgdal 包从 PostGIS 获取所需数据的方法。可能是因为我的操作系统问题。 (我不太确定,因为我不是专家)。但我找到了 rgdal 的替代品,它完全按照我的意愿完成了工作。代码如下:

library(RPostgreSQL)
library(rgeos)
library(sp)

# Load data from the PostGIS server
conn = dbConnect(
  dbDriver("PostgreSQL"), dbname="dbNAME", host="localhost", port=5432, 
  user="username", password="pw"
)

strSQL = "SELECT osm_id, name, area, highway, railway, place, ST_AsText(way) AS wkt_geometry FROM table"
df = dbGetQuery(conn, strSQL)

#Geomtery column as R list
geo_col = df$wkt_geometry

polygon_list = suppressWarnings(lapply(geo_col, function(x){
x <- gsub("POLYGON\\(\\(", "", x)
x <- gsub("\\)", "", x)
x <- strsplit(x, ",")[[1]]

#Now each polygon has been parsed by removing POLYGON(( from the start and )) from the end
#Now for each POLYGON its xValues and yValues are to be extracted to for Polygon object
xy <- strsplit(x, " ")

v_xy = suppressWarnings(sapply(xy, function(p){        
  xValue = p[1]
  yValue = p[2]
  vec = c(xValue, yValue)
}))

#Now we have all x values in first column of v_xy and all y values in second column of v_xy
#Let us make the Polygon object now
p_xvalues = as.numeric(v_xy[1, ])
p_yvalues = as.numeric(v_xy[2, ])
p_object <- Polygon(cbind(p_xvalues, p_yvalues))      
}))

#Now we have all of the polygons in polygon object format
#Let us join it with main data frame, i.e. df
df$object_polygon <- polygon_list
#View(df)

#Now Let us form SpatialPolygons() object out of it
Ps_list = list()
for (i in seq(nrow(df))) {
  Ps_list[[i]] <- Polygons(polygon_list[i], ID=df[i,][1])
}
SPs = SpatialPolygons(Ps_list)

#Now FINALY its the time to form SpatialPolygonsDataFrame
row.names(df) = df$osm_id
SPDF = SpatialPolygonsDataFrame(Sr = SPs, data = df[, 1:6], match.ID = TRUE) 

因此,基本上我必须编写一个解析器来获取所需的数据,其中 readOGR() 一行完成。

关于r - 如何将 OSM 多边形数据从 PostGIS 导入到 R?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34643973/

相关文章:

json - Postgres : How to convert a json string to text?

javascript - 有没有可能将 postgreSQL 直接连接到 Javascript?

postgresql - 如何在 PostgreSQL 中添加新的数据结构?

RGoogleDocs 身份验证失败

r - knitr:在报告中包含数字*和*输出数字以分隔文件

postgresql - 如何准确存储地理位置数据,在半径范围内进行过滤,计算距离?

python - PostGIS 中多边形内的点

postgresql - JPA 与很多 child 建立父/子关系

r - 在 R 中,如何更改行和列的位置?

r - 在读取多个 CSV 文件时,base R 比 readr 更快