在R中实现从指定点生成角度线段并与多边形相交时截断
在R中生成带截断功能的径向线段(测量点到多边形的距离)
我需要在R中创建指定长度的线Shapefile,线段从指定点出发并按特定角度延伸。当线段与多边形相交时将其截断,以此测量初始点到多边形的距离。
Polygons_sf 是亚速尔群岛的多边形Shapefile,sightsLand 是包含多个海上点的点Shapefile,线段将从这些点出发。
初始实现:生成径向线段
以下代码已实现从指定点生成特定角度的线段(radial_line_sf),但尚未实现线段与多边形重叠时的截断功能:
# 加载所需包 library(sf) library(ggplot2) # 读取Shapefile polygon_sf <- read_sf("CAOP_RAA_2022-shp/ArqAcores/ArqAcores_GCentral_AAd_CAOP2022.shp") polygon_sf <- st_transform(polygon_sf, crs = 4326) st_crs(polygon_sf) sights <- read_sf("Sightings.shp") sightsLand <- subset(sights, sights$RetclLn == "LA") # 提取点的经纬度坐标 point_location <- st_coordinates(sightsLand[1, "geometry"]) # 创建单条径向线段 angle_degrees <- 55 # 指定角度 line_length <- 0.25 # 调整线段长度 angle_rad <- angle_degrees * (pi / 180) # 角度转弧度 end_lat <- point_location[2] + line_length * sin(angle_rad) end_lon <- point_location[1] + line_length * cos(angle_rad) matrix_coords <- rbind(c(point_location[1], point_location[2]), c(end_lon, end_lat)) radial_line_sf <- st_sfc(st_linestring(matrix_coords), crs = 4326) # 绘制多边形、点和径向线段 ggplot() + geom_sf(data = polygon_sf, fill = "lightblue", color = "black") + geom_sf(data = sightsLand[1,28], color = "red", size = 3, shape = 18) + geom_sf(data = radial_line_sf, color = "blue") + theme_minimal()
初始效果示意图:
实现线段截断功能
通过以下代码可实现线段与多边形相交处的截断,提取初始点到交点的线段部分:
# 截断线段 line_not_overlapping <- lwgeom::st_split(radial_line_sf, polygon_sf) # 从GEOMETRYCOLLECTION中提取第一条LineString first_line <- line_not_overlapping[[1]][[1]] # 创建新的sf对象存储截断后的线段 first_line_sf <- st_sf(geometry = st_sfc(first_line)) # 设置与原数据相同的CRS st_crs(first_line_sf) <- st_crs(line_not_overlapping)
截断后的效果示意图:
内容的提问来源于stack exchange,提问作者Catarina Toscano
相关产品推荐
相关产品推荐

