问题
Inputs
I have two shapefiles that I Import into R, so that I end up with. A spatiallinesdataframe containing bus routes. A spatialpointsdataframe containing bus stops.
Plotting a given route with its stops looks like this.
Sample Data
This link includes two shapefiles to download as a zip with a sample two routes.
Target
My aim is to calculate the geographic distance in meters between every pair of stops: Stop 1 to Stop 2, Stop 2 to Stop 3, etc. across the length of the underlying bus route.
Most methods I found calculate the euclidean distance, or as 'the crow flies'; which will not work here.
This post mentions the PBSmapping
which has a calcLength
function that does a great job calculating the total distance of the route, but I can't find a way to match it to the stop pairs situation, nor can I find a way to actually subset the shapefile by its attributes.
The riverdist
package is equally interesting, but highly optimized for rivers that I can't find a way to apply it.
回答1:
Try gProject
from the rgeos
package:
library("rgdal")
library("rgeos")
# read shapefile and transfrom to UTM zone 36N (distances in m)
route <- spTransform(readOGR(".", "Trips"), CRS("+init=epsg:32636"))
stops <- spTransform(readOGR(".", "Stops"), CRS("+init=epsg:32636"))
l <- subset(route, route_id==1137)
p <- subset(stops, grepl("^1137_", UID))
plot(l, axes=TRUE, col="orange")
plot(p, add=TRUE, pch=19, cex=0.1)
text(p)
# distance along route
d <- sort(gProject(l, p))
d
# [1] 0 3051 3057 7221 10379 15657 20326 20326 22141 24262
# distance between stops
diff(d)
#[1] 3050.9166 5.9720 4164.2480 3157.7702 5278.5812 4668.1810 0.5878
#[8] 1814.9612 2120.8470
来源:https://stackoverflow.com/questions/49760063/how-to-calculate-geographic-distance-between-two-points-along-a-line-in-r