【发布时间】:2022-08-10 18:15:18
【问题描述】:
尝试使用每个 sf 线串的起点和终点来计算线串的 sf 向量的角度。我不想拆线。
我在这个类似的例子中使用了公式来计算度数 Calculate angle between two Latitude/Longitude points
下面的示例下载了一个小型道路网络,创建了一个函数 \'angles\',它在数据框中添加一个带有角度的列,然后在 mapview 中绘制它,因此每条线都按角度着色。但是,这些值不正确。我认为公式的简单错误?
library(osmdata)
library(sf)
library(dplyr)
bb <- st_bbox(c(xmin = 5.22, xmax = 5.246, ymax = 52.237, ymin = 52.227), crs = st_crs(4326))
x <- opq(bbox = bb) %>%
add_osm_feature(key = c(\'highway\')) %>%
osmdata_sf()
##extract building polygons
roads <- x$osm_lines %>%
filter(highway == \"motorway\") %>%
select(osm_id, geometry)
angles <- function(x){
## define line finish coordinates
f <- x %>%
st_transform(28992) %>%
st_line_sample(sample = 1) %>%
st_cast(\"POINT\") %>%
st_transform(4326) %>%
st_coordinates()
## define line start coordinates
s <- x %>%
st_transform(28992) %>%
st_line_sample(sample = 0) %>%
st_cast(\"POINT\") %>%
st_transform(4326) %>%
st_coordinates()
## get latitude of finish points
lat2 <- f[,2]
## get latitudes of start points
lat1 <- s[,2]
## get longitudes of start points
lon2 <- f[,1]
## get longitudes of start points
lon1 <- s[,1]
## delta longitudes
#dlon <- f[,1]-s[,1]
#theta <- (atan2(sin(dlon)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(dlon)))*180/pi
theta <- atan2(lat2-lat1, lon2-lon1)*180/pi
x$angle_deg <- theta
return(x)
}
a <- angles(roads) %>%
select(angle_deg)
library(mapview)
mapview(a)