1

I have a large rivernetwork as a SpatialLines(DataFrame) and want to subset it so I get a SpatialLine with only the shortest/fastest path between two SpatialPoints(DataFrame) which propably need to be snapped onto the line first.

In the example Code, I want to get the closest line between the red dots, while moving on the lines. Also I want to move between the left red point and the right blue point, which needs to be snapped to the closest SpatialLine

library(sp)    
x <- c(1,5,6,8)
y1 <- c(1,3,4,7)
y2 <- c(5,5,5,2)

L <- SpatialLines(list(Lines(Line(cbind(x,y1)), ID="a"),Lines(Line(cbind(x,y2)), ID="b")))
P <- SpatialPoints(data.frame(x=c(1,8),y=c(1,2)))
P_snap <- SpatialPoints(data.frame(x=c(8),y=c(1)))

plot(L)
points(P,col="red")
points(P_snap,col="blue")
0

apologies for all these libraries, i'm not sure exactly which is needed... Good luck! this is kind of complicated. and not exactly sure how it works.

library(igraph)
library(RColorBrewer)
library(SpatialTools)
library(sp)
library(ANN)
library(rgeos)
library(maptools)
library(sp)
library(rgeos)
library(plyr)
library(FNN)
library(tidyr)
library(foreign)
library(dplyr)
library(plyr)
library(reshape)


buildTopo <- function(lines) {

  g = gIntersection(lines, lines)
  edges = do.call(rbind, lapply(g@lines[[1]]@Lines, function(ls) {
    as.vector(t(ls@coords))
  }))
  lengths = sqrt((edges[, 1] - edges[, 3])^2 + (edges[, 2] - edges[, 4])^2)

  froms = paste(edges[, 1], edges[, 2])
  tos = paste(edges[, 3], edges[, 4])

  graph = graph.edgelist(cbind(froms, tos), directed = FALSE)
  E(graph)$weight = lengths

  xy = do.call(rbind, strsplit(V(graph)$name, " "))

  V(graph)$x = as.numeric(xy[, 1])
  V(graph)$y = as.numeric(xy[, 2])
  return(graph)
}

routePoints <- function(graph, from, to) {
  require(FNN)
  xyg = cbind(V(graph)$x, V(graph)$y)

  ifrom = get.knnx(xyg, from, 1)$nn.index[1, 1]
  ito = get.knnx(xyg, to, 1)$nn.index[1, 1]

  p = get.shortest.paths(graph, ifrom, ito, output = "vpath")
  p[[1]]
}

buildTopo() use this function to create a topographically correct object. The input is a SpatialLinesDataFrame

Then use routePoints(ResultOfbuildTopo, FromCoord, ToCoord)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.