Hi,<br><br><br>This post could have followed the one about shortest path but I preferred to make a separate post to make things clearer.<br><br>Given a set of points and a set of lines, I tried to make a graph of it. The operation consisted, firstly, in getting the lines that connect each point to the nearest point on the segment pattern<br>
<br>For this, I used spatstat::project2segment. spatstat is really a wonderful package. I think it can be useful for snapping line operations.<br><br>I'm stuck because I manage to create some lines between the points and the segments but some lines connect to the network while others don't. <br>
<br>When they don't, the distance between the end connecting segment point and the network is extremely small. I put an image of it as attached file.<br><br>Here is the code, for those who'd like to give it a try and, eventually, give an issue. Maybe I did it in a wrong way. It's based on Barry's initial code.<br>
<br>library(spatstat)<br>library(rgeos)<br>library(maptools)<br><br>makeNest <- function(n) {<br> ### generate a bunch of SpatialLines on (0,1) square<br> xy = cbind(runif(n), runif(n), runif(n), runif(n))<br> lines = Lines(apply(xy, 1, function(z) {<br>
Line(rbind(z[1:2], z[3:4]))<br> }), ID = 1)<br> SpatialLines(list(lines))<br>}<br><br>connection2Lines <- function(lines, pts){<br> <br> sourcePts <- as(pts,"ppp")<br> projectedPts <- project2segment(sourcePts, as(lines, "psp"))$Xproj<br>
bb <- union.owin(bounding.box(sourcePts), bounding.box(projectedPts))<br> cnnLines <- as(psp(sourcePts$x, sourcePts$y, projectedPts$x, projectedPts$y, window=bb), "SpatialLines")<br> cnnLines <- spChFIDs(cnnLines, sapply(cnnLines@lines, function(x) paste("connect", x@ID, sep="_")))<br>
proj4string(cnnLines) <- proj4string(lines) <br> <br> return(cnnLines)<br>}<br><br>n <- 5<br>pts <- SpatialPoints(cbind(runif(n), runif(n)))<br><br>gg = makeNest(10)<br><br>cnnLines <- connection2Lines(gg, pts)<br>
<br>plot(gg)<br>plot(cnnLines, col="red", add=T)<br><br>any(gIntersects(cnnLines, gg, byid=TRUE)==FALSE)<br>