在给定点的多边形内创建线 [英] Create lines within polygons at given points
本文介绍了在给定点的多边形内创建线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个空间多边形
library(sf)
df <- data.frame(
lon = c(119.4, 119.4, 119.4, 119.5, 119.5),
lat = c(-5.192, -5.192, -5.167, -5.167, -5.191)
)
polygon <- df %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON")
里面有几个点
df2 <- data.frame(
lon = c(119.45, 119.49, 119.47),
lat = c(-5.172, -5.190, -5.183)
)
points <- df2 %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("MULTIPOINT")
如何通过每个点绘制一条从多边形的一端到另一端的水平线?也就是说,在多边形内绘制三条直线,每条直线穿过其中一个点。我发现了几个绘制连接点或使用点作为起点和终点的线条的例子,但在我的例子中,这些点只是标记所需的水平线的y值。
提前谢谢!
推荐答案
此方法只是在点上循环,并使用POLYGON
的x坐标和POINT
的y坐标创建一个新的LINESTRING
对象:
library(sf)
library(dplyr)
df <- data.frame(
lon = c(119.4, 119.4, 119.4, 119.5, 119.5),
lat = c(-5.192,-5.192,-5.167,-5.167,-5.191)
)
polygon <- df %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON")
plot(polygon)
df2 <- data.frame(lon = c(119.45, 119.49, 119.47),
lat = c(-5.172,-5.190,-5.183))
points <- df2 %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("MULTIPOINT")
plot(points, add = TRUE, col = "red")
# Solution via a loop
xminmax <- c(min(df$lon), max(df$lon))
# Iterate and create lines
for (i in 1:3) {
l <- st_linestring(matrix(
c(xminmax[1],
df2[i, "lat"],
xminmax[2],
df2[i, "lat"]),
nrow = 2,
byrow = TRUE
))
# Create final object line
if (i == 1) {
line <- l
} else {
line <- c(line, l)
}
}
# Result is line MULTILINESTRING object
plot(line, col = "green", add = TRUE)
由reprex package(v1.0.0)在2021-02-15创建
这篇关于在给定点的多边形内创建线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文