st_intersection 具有 POLYGON 边界的 LINESTRING,同时保留 r / sf 中点的顺序
st_intersection LINESTRING with borders of POLYGONs while preserving the order of points in r / sf
我需要将 LINESTRING
与边界 POLYGON
要素相交,同时保留生成的 POINT
要素的顺序。背景是我需要弄清楚汽车在 entering/leaving 特定国家/地区的过境点,但过境点的顺序很重要。
我已经实施了以下方法:
# setup test data
poly <-
list(matrix(c(0,0,10,0,10,10,0,10,0,0),ncol=2, byrow=TRUE)) %>%
sf::st_polygon() %>%
sf::st_sfc() %>%
sf::st_sf()
line1 <- matrix(c(-1, 10, 5, -1),ncol=2, byrow=TRUE) %>%
sf::st_linestring() %>%
sf::st_sfc() %>%
sf::st_sf()
# reverse of line 1
line2 <- matrix(c(5, -1, -1, 10), ncol=2, byrow=TRUE) %>%
sf::st_linestring() %>%
sf::st_sfc() %>%
sf::st_sf()
# preview
leaflet::leaflet() %>%
leaflet::addPolygons(data = poly) %>%
leaflet::addPolylines(data = line1) %>%
leaflet::addPolylines(data = line2) %>%
leaflet::addTiles()
# do the intersection
# cast to multilinestring because I just need the border crossing points
ml <- sf::st_cast(poly, "MULTILINESTRING")
sf::st_intersection(ml, line1)
sf::st_intersection(ml, line2)
但是,这种方法丢失了过境点的顺序。有人有更好的主意吗?
我找到了一个涉及 rgeos::gProject()
的答案。这个函数计算沿直线的点之间的距离,我可以用它来推导我的点的排序顺序:
# do the intersection
ml <- sf::st_cast(poly, "MULTILINESTRING")
points1 <- sf::st_intersection(ml, line1) %>%
sf::st_cast("POINT")
points2 <- sf::st_intersection(ml, line2) %>%
sf::st_cast("POINT")
# Calculate sort order for the points
points1$order <- rgeos::gProject(sf::as_Spatial(line1), sf::as_Spatial(points1))
points2$order <- rgeos::gProject(sf::as_Spatial(line2), sf::as_Spatial(points2))
我需要将 LINESTRING
与边界 POLYGON
要素相交,同时保留生成的 POINT
要素的顺序。背景是我需要弄清楚汽车在 entering/leaving 特定国家/地区的过境点,但过境点的顺序很重要。
我已经实施了以下方法:
# setup test data
poly <-
list(matrix(c(0,0,10,0,10,10,0,10,0,0),ncol=2, byrow=TRUE)) %>%
sf::st_polygon() %>%
sf::st_sfc() %>%
sf::st_sf()
line1 <- matrix(c(-1, 10, 5, -1),ncol=2, byrow=TRUE) %>%
sf::st_linestring() %>%
sf::st_sfc() %>%
sf::st_sf()
# reverse of line 1
line2 <- matrix(c(5, -1, -1, 10), ncol=2, byrow=TRUE) %>%
sf::st_linestring() %>%
sf::st_sfc() %>%
sf::st_sf()
# preview
leaflet::leaflet() %>%
leaflet::addPolygons(data = poly) %>%
leaflet::addPolylines(data = line1) %>%
leaflet::addPolylines(data = line2) %>%
leaflet::addTiles()
# do the intersection
# cast to multilinestring because I just need the border crossing points
ml <- sf::st_cast(poly, "MULTILINESTRING")
sf::st_intersection(ml, line1)
sf::st_intersection(ml, line2)
但是,这种方法丢失了过境点的顺序。有人有更好的主意吗?
我找到了一个涉及 rgeos::gProject()
的答案。这个函数计算沿直线的点之间的距离,我可以用它来推导我的点的排序顺序:
# do the intersection
ml <- sf::st_cast(poly, "MULTILINESTRING")
points1 <- sf::st_intersection(ml, line1) %>%
sf::st_cast("POINT")
points2 <- sf::st_intersection(ml, line2) %>%
sf::st_cast("POINT")
# Calculate sort order for the points
points1$order <- rgeos::gProject(sf::as_Spatial(line1), sf::as_Spatial(points1))
points2$order <- rgeos::gProject(sf::as_Spatial(line2), sf::as_Spatial(points2))