应该很容易:R中沿着一条线的距离?

时间:2015-03-08 03:53:43

标签: r gis distance 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")

1 个答案:

答案 0 :(得分:0)

可以使用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 = rnet, 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