2
votes

Is there a way to calculate the maximum distance between two polylines? I'm currently using the sf package to get the minimum distance, but I also need the maximum distance see the example below.

pts1<- data.frame(
  x= c(-103.485342, -103.482808),
  y = c(31.348758, 31.376947))
) %>% 
  sf::st_as_sf(coords = c("x","y"))

st_crs(pts1)<- "+init=epsg:2257"

pts2<- data.frame(
  x= c(-103.492822, -103.484231),
  y = c(31.348181, 31.377191))
) %>% 
  sf::st_as_sf(coords = c("x","y"))

st_crs(pts2)<- "+init=epsg:2257"

a <- pts1 %>% st_coordinates() %>% st_linestring()
b<- pts2 %>% st_coordinates() %>% st_linestring()

min_dist<-st_distance(a,b,by_element = T)

max_dist<- ???

Thanks

1
There's some extra ) where you are defining your data frames. The code doesn't run.Spacedman

1 Answers

3
votes

The maximum distance (in a planar geometry) should always be between two vertexes, so cast to points, compute the distance matrix between the points of a and the points of b, and take the maximum:

> max(st_distance(st_cast(st_sfc(b),"POINT"),st_cast(st_sfc(a),"POINT")))
[1] 0.0304592

Note this is the distance along the dotted red line:

enter image description here

It might be that these two lines of yours represent something like the banks of a river and your real question is "how wide is the river at its widest", which would be between the two most southerly points in your example, but that's a different question to "what's the greatest distance between two lines".