R中存在gBuffer的困难:结果缓冲区大小不正确

时间:2019-04-22 16:48:58

标签: r geolocation buffer

此代码的总体目标是根据需要输入的单个经度/纬度点在循环缓冲区内生成随机点。我的明显问题是,从gBuffer生成的缓冲区的大小/位置不正确,因此,这些点比输入位置要远比期望的远。

我正在尝试在一个点周围创建130米的缓冲区。为了构造我的代码,我一直在使用44.55555, -68.55555。我使用的是十进制经度/纬度,因为这就是我的数据所在的位置。

我尝试了多个stackoverflow线程来找到答案,包括: Buffer (geo)spatial points in R with gbuffer Create buffer and count points in R

#Enter in the lat and Long
NestLat <- readline(prompt="Enter Nest Latitude:") #Use 44.55555 
NestLong <- readline(prompt="Enter Nest Longitude:") #Use -68.55555

#Coordinate from text to spatial points
NestLat <- as.numeric(NestLat)
NestLong <- as.numeric(NestLong)

nestcoords <- cbind(NestLat, NestLong)
nestcoords_sp <- SpatialPoints(nestcoords, proj4string=CRS("+proj=longlat +datum=WGS84"))
nestcoords_sp <- spTransform(nestcoords_sp, CRS("+init=epsg:2960"))

#Create buffer to generate 3 random points within 130m of nest
nestbuffer130 <- gBuffer(nestcoords_sp, width = 130)
nestbuffer130 <- spTransform(nestbuffer130, CRS("+proj=longlat +datum=WGS84"))

randoms130 <- spsample(nestbuffer130, 3, type = "random")
randoms130 <- spTransform(randoms130, CRS("+proj=longlat +datum=WGS84"))

nestbuffer130spdf <- as(nestbuffer130, "SpatialPolygonsDataFrame")
randoms130 <- as(randoms130, "SpatialPointsDataFrame")

最终缓冲区似乎是半径为335的圆,并且没有在空间上正确放置。

1 个答案:

答案 0 :(得分:0)

您如何测量半径?如果您只想将采样点放在正确的位置,该代码似乎可以正常工作。这是使用gDistance函数稍作修改的代码,显示您的点在缓冲区内。 SF现在是R的首选空间包,语法更清晰,更容易。我添加了SF软件包的代码。

library(rgeos)
library(sp)
#Enter in the lat and Long
NestLat <- 44.55555 
NestLong <- -68.55555

#Coordinate from text to spatial points
NestLat <- as.numeric(NestLat)
NestLong <- as.numeric(NestLong)

nestcoords <- cbind(NestLat, NestLong)
nestcoords_sp <- SpatialPoints(nestcoords, proj4string=CRS("+proj=longlat +datum=WGS84"))
nestcoords_sp <- spTransform(nestcoords_sp, CRS("+init=epsg:2960"))

#Create buffer to generate 3 random points within 130m of nest
nestbuffer130 <- gBuffer(nestcoords_sp, width = 130)
randoms130 <- spsample(nestbuffer130, 3, type = "random")
nestbuffer130spdf <- as(nestbuffer130, "SpatialPolygonsDataFrame")
randoms130 <- as(randoms130, "SpatialPointsDataFrame")

# measure distance
gDistance(randoms130, nestcoords_sp, byid = T)

SF

library(sf)
# turn coordinates into spatial poitns using sf
NestLat <- 44.55555 
NestLong <- -68.55555
nestPoints <- st_point(c(NestLong,NestLat)) %>%
  st_sfc(crs = 4326) %>% 
  st_transform(crs = 2960)
mapview(randoms130) + nestPoints

#Create buffer to generate 3 random points within 130m of nest
nestbuffer130 <- st_buffer(nestPoints, dist = 130)
randoms130 <- st_sample(nestbuffer130, 3)

# measure distance between points
st_distance(nestPoints,randoms130)
nestbuffer130SF <- st_sf(data = data.frame(ID = 1:length(randoms130)),
                         geometry = randoms130, crs = st_crs(randoms130)) %>% 
  st_transform(crs = 4326)

# check data visually
library(mapview)
mapview(nestbuffer130SF) + nestPoints