找到点矢量和R中多边形之间的最近距离

时间:2016-09-01 16:38:46

标签: r polygon distance points

我有一个lat / long坐标的数据框和一个代表海岸线的多边形。我试图找到每个点和最近的海岸线特征之间的距离。我想最终得到一个输出数据框,其中包含原始纬度/经度值和新距离列的列。

我在网上阅读了类似问题的答案之后尝试使用gDistance功能,但我认为我错过了一些步骤并且无法搞清楚。目前,我最终只有一个距离值。我是R的新手,非常感谢任何人都能给予的任何帮助。

谢谢!

#Load data
     Locs = structure(list(id = 1:5, Lat = c(29.59679167, 29.43586667, 29.37642222,29.52786111, 30.10603611), Long = c(-81.02547778, -80.92573889, 
-80.97714167, -81.08721667, -80.94368611)), .Names = c("id","Lat", "Long"), class = "data.frame", row.names = c(NA, -5L))

#Extract lat/long coordinates
   xy = Locs[,c("Lat","Long")]
#Create SpatialPointsDataFrame from xy data and change projection to metres
   spdf = SpatialPointsDataFrame(coords=xy, data=xy, proj4string = CRS("+proj=aea +zone=17 ellps=WGS84"))

#Read in shapefile as a spatialdataframe object 
  coast = readOGR(dsn="land data", layer="coast")    
#Transform to AEA (m) projection to match projection of points
   land_poly = spTransform(coast, CRS("+proj=aea +zone=17 ellps=WGS84"))

#OR load map from map package (but unfortunately map objects do not work in gDistance)
   library(maps)  
   library(mapdata)
   coast2 = map('usa', col = "grey90", fill=TRUE)

#Calculate distance between each point and the nearest land feature
  for(i in 1:dim(spdf)[1]){
  g = gDistance(spdf[i,],land_poly)
  }

编辑:使用下面的AEF代码更改(对于for循环步骤),我能够获得每行的gDistance值,但输出距离不正确(见下文)。根据arcGIS,它们应该在4-37km之间,而不是> 500km。对我在这里做错了什么的想法?我的陆地多边形和点都在同一个投影中。

gDistance输出

  id      Lat      Long dist_gDist
1  1 29.59679 -81.02548  516299.0
2  2 29.43587 -80.92574  516298.8
3  3 29.37642 -80.97714  516298.9
4  4 29.52786 -81.08722  516299.0
5  5 30.10604 -80.94369  516299.0

正确的距离(在GIS中计算)

  id      Lat      Long dist_arc
1  1 29.59679 -81.02548  13.630
2  2 29.43587 -80.92574  15.039
3  3 29.37642 -80.97714  8.111
4  4 29.52786 -81.08722  4.784
5  5 30.10604 -80.94369  36.855

1 个答案:

答案 0 :(得分:1)

我认为您只获得一个距离值,因为您在g - 循环的每次迭代中都会覆盖for。但我不知道这是否是唯一的问题,因为如果没有合适的数据,我无法重现您的问题。 尝试将最后一个循环更改为:

g = rep(NA, dim(spdf)[1])
for(i in 1:dim(spdf)[1]){
  g[i] = gDistance(spdf[i,],land_poly)
}