如何使用R和sf从两个点构建矩形?

soat7uwm  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(115)

我想用R和软件包sf构建一个矩形,这个矩形必须开始和结束于两个给定的点:

library(sf)
library(units)

>     point1$geometry
Geometry set for 1 feature 
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -73.51295 ymin: 45.529 xmax: -73.51295 ymax: 45.529
Geodetic CRS:  WGS 84
POINT (-73.51295 45.529)
>     point2$geometry
Geometry set for 1 feature 
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -73.51347 ymin: 45.52816 xmax: -73.51347 ymax: 45.52816
Geodetic CRS:  WGS 84
POINT (-73.51347 45.52816)

字符串
我定义了中心和矩形的大小

center <- st_point(c((st_coordinates(point1)[1] + st_coordinates(point2)[1]) / 2,
                         (st_coordinates(point1)[2] + st_coordinates(point2)[2]) / 2))
    half_width <- as.numeric(st_distance(point1, point2) / 2)
    constant_half_height <- 100 / 111000  # 1 degree is approximately 111,000 meters
    half_width <- half_width / 111000  # 1 degree is approximately 111,000 meters
constant_half_height <- set_units(100, "meters")


然后我建了一个长方形

corners <- rbind(
      st_coordinates(center) + c(-half_width, -constant_half_height),
      st_coordinates(center) + c(half_width, -constant_half_height),
      st_coordinates(center) + c(half_width, constant_half_height),
      st_coordinates(center) + c(-half_width, constant_half_height),
      st_coordinates(center) + c(-half_width, -constant_half_height)
    )
    
    rectangle <- st_polygon(list(st_linestring(corners)))


但我不能有正确的矩形,因为我希望它遵循点azymuthal角


的数据

hpxqektj

hpxqektj1#

如果你创建了一条从point1point2的直线,并添加了一个具有平坦直线末端的缓冲区,你应该最终得到所描述的矩形(/../必须在两个给定的点开始和结束/../跟随点azymuthalAngular /../)。尽管对于这样的缓冲区选项,你需要禁用s2(sf_use_s2(use_s2 = FALSE))或使用投影坐标。

library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(ggplot2)
library(ggspatial)

point1 <- 
  data.frame(geometry = "POINT (-73.51295 45.529)") |> 
  st_as_sf(wkt = "geometry", crs = "WGS84") 
point2 <-
  data.frame(geometry = "POINT (-73.51347 45.52816)") |> 
  st_as_sf(wkt = "geometry", crs = "WGS84") 

# transform to projected CRS first; and back to WGS84, if needed
poly_sf <- 
  rbind(point1, point2) |> 
  # UTM 18N
  st_transform(32618) |>
  st_combine() |>
  st_cast("LINESTRING") |>
  st_buffer(dist = 10, endCapStyle="FLAT") |>
  st_transform("WGS84")

st_as_text(poly_sf)
#> [1] "POLYGON ((-73.51335 45.52812, -73.51359 45.5282, -73.51307 45.52904, -73.51283 45.52896, -73.51335 45.52812))"

ggplot() + 
  annotation_map_tile(zoomin = 0 ) +
  geom_sf(data = poly_sf, alpha = 0.6, fill = "gold") +
  geom_sf(data = rbind(point1, point2), size = 3) +
  theme_void()

字符串
x1c 0d1x的数据
创建于2023-12-14使用reprex v2.0.2

相关问题