Extract routes between stations from a rail network shapefile
<p>Problem: I want to extract a route along the rail network between two stations from a shapefile and only plot this particular route, rather than the entire network. </p>

<p>This is what I have so far: </p>

<p>I have a shapefile with the entire rail network of the UK, plotted it looks like this: </p>

<pre><code>library(maptools)
rail &lt;- readShapeSpatial("railnetworkLine.shp")
</code></pre>

<p><a href="https://i.stack.imgur.com/RDUF9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/RDUF9.jpg" alt="enter image description here"></a></p>

<p>I also have a list of stations with Eastings and Northings, for example:</p>

<pre><code> 1) ABDARE 300400 202800
 2) DEIGHTN 416490  419140
</code></pre>

<p>I can add them to the map and it looks like this: </p>

<pre><code>plot(rail)
plot(spdf.station, add=TRUE, col="red", pch=20)
</code></pre>

<p><a href="https://i.stack.imgur.com/8PLnv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8PLnv.jpg" alt="enter image description here"></a></p>

<p>So what I don't know, is how I can extract the route between them and just plot that route - the information is obviously in the shapefile and I have the coordinates of the station, but I don't understand how to extract it. </p>

<p>I managed to calculate the distance between them with this code: </p>

<pre><code>SpacingInMetres &lt;- 10000
require(secrlinear)
network &lt;- read.linearmask(data=rail, spacing=SpacingInMetres)
distance &lt;- (networkdistance (stations[1,], stations[2,], network))/1000

# Confirm distance:
distance
&gt;311.7893
</code></pre>

<p>And I found that you can get the routes along roads with Google Maps with <code>ggmaps</code> (see <a href="https://stackoverflow.com/questions/17282124/how-do-i-get-driving-time-from-google-maps-api/17282224#17282224">here</a>). But how can you do it when you have a shapefile as the network input rather than Google Maps?</p>

<p>I think maybe the packages 'shp2graph' + 'igraph' are useful, but I just can't figure it out. Any thoughts?</p>