r - 应该很容易 : distance along a line in R?

标签 r gis distance shapefile

我在莫桑比克有一个铁路的 Shapefile,并使用下面的代码在铁路上生成了 100 个随机点。

我的问题很简单,但我找不到答案:你如何计算铁路沿线点之间的距离?

我不想要欧几里得距离,我想要沿着铁轨从 A 点到 B 点的距离。

提前致谢!

library(sp)
library(rgdal)
library(spgrass6)
library(maptools)
library(igraph)
library(fields)

railroads <- readShapeLines("MOZ_rails.shp")

#Generate 100 random points, and put them on a matrix:
RandomPoints<-spsample(railroads, 100, type="random")

最佳答案

可以使用 stplanr 包计算路由网络上的最短路径。我在荷兰的整个铁路网络中使用了一个 shapefile。此 shapefile 可从以下位置获得:
https://mapcruzin.com/free-netherlands-arcgis-maps-shapefiles.htm

library(sf)
library(ggplot2)
library(stplanr)

# Read shapefile
nl_rails_sf <- sf::st_read("~/netherlands-railways-shape/railways.shp")

# Generate 100 random points
set.seed(12345)
RandomPoints <- sf::st_sample(nl_rails_sf, 100, type = "random", exact = TRUE)
X <- st_coordinates(RandomPoints)[,1]
Y <- st_coordinates(RandomPoints)[,2]

# Find shortest route
slnetwork <- SpatialLinesNetwork(nl_rails_sf) 
find_nodes <- find_network_nodes(sln = slnetwork, x = X, y = Y, maxdist = 2e6)
route_dhdb_df <- expand.grid(start = find_nodes, end = find_nodes) %>% 
    mutate(id_route = 1:nrow(.))
route_dhdb_sf <- sum_network_links(sln = slnetwork, routedata = route_dhdb_df)

# Route length
route_dhdb_sf %>% 
    group_by(id_route) %>% 
    summarize(length = sum(length))

# Plot results
ggplot(nl_rails_sf) +
   geom_sf() +
   theme_void() +
   geom_sf(data = RandomPoints, color = "red") +
   geom_sf(data = route_dhdb_sf, color = "red")
enter image description here

关于r - 应该很容易 : distance along a line in R?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28922874/

相关文章:

python - 跨多个地理围栏的地理围栏半径分布/比率

excel - 用于确定位置之间距离的方法/工具

r - 证明 ggplot 中的标签和标签透明度

r - R Flexdashboard 中的下载按钮宽度

r - 无论操作系统如何,如何使 CRAN 包只下载一次数据?

distance - Kademlia XOR度量标准属性用途

C、计算两个 GPS 位置之间的距离?

R - dplyr 风格化打印或粘贴

python - Python 列表切片与 R 向量切片

r - 如何将 map 投影从太平洋中心更改为大西洋中心?