坐标中的多边形 [英] polygons from coordinates

查看:76
本文介绍了坐标中的多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.frame,其中lat s和lng s定义了矩形框的边界,就像这样

I've got a data.frame with lats and lngs that define the boundaries of rectangular boxes, like so

  geohash north_lat south_lat  east_lng  west_lng
1   gbsuv  48.69141  48.64746 -4.306641 -4.350586
2   gbsuy  48.69141  48.64746 -4.262695 -4.306641

将其转换为包含POLYGON s列的sf对象的最简单方法是什么?

What's the easiest way to convert this into an sf object that holds a column of POLYGONs?

推荐答案

创建多边形的关键是坐标必须按顺序形成一个封闭区域(即,最后一个点与第一个点相同) .

The key to creating polygons is that the coordinates have to be in sequence to form a closed area (i.e., the last point is the same as the first point).

因此,您的数据将需要一些操作才能创建坐标,并将其整理好.在我的示例中,我使用lapply

So your data will need a bit of manipulation to create the coordinates, and put them in order. In my example I've done this with an lapply

然后可以从 sf示例

lst <- lapply(1:nrow(df), function(x){
  ## create a matrix of coordinates that also 'close' the polygon
  res <- matrix(c(df[x, 'north_lat'], df[x, 'west_lng'],
           df[x, 'north_lat'], df[x, 'east_lng'],
           df[x, 'south_lat'], df[x, 'east_lng'],
           df[x, 'south_lat'], df[x, 'west_lng'],
           df[x, 'north_lat'], df[x, 'west_lng'])  ## need to close the polygon
         , ncol =2, byrow = T
  )
  ## create polygon objects
  st_polygon(list(res))

})

## st_sfc : creates simple features collection
## st_sf : creates simple feature object
sfdf <- st_sf(geohash = df[, 'geohash'], st_sfc(lst))

sfdf
# Simple feature collection with 2 features and 1 field
# geometry type:  POLYGON
# dimension:      XY
# bbox:           xmin: 48.64746 ymin: -4.350586 xmax: 48.69141 ymax: -4.262695
# epsg (SRID):    NA
# proj4string:    NA
# geohash                    st_sfc.lst.
# 1   gbsuv POLYGON((48.69141 -4.350586...
# 2   gbsuy POLYGON((48.69141 -4.306641...

plot(sfdf)

这篇关于坐标中的多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆