user3857437
user3857437

Reputation: 57

Find nearest distance from spatial point with direction specified

I would like to calculate the nearest distance from a spatial point to spatial lines (or polygons) for predetermined bearings (0,45,90,135,180,225,270,315).

The idea is to calculate an exposure index for a number of bays along a coastline. A simple example is provided below:

Create lines

library(sp)
coords<-structure(list(lon = c(-6.1468506, -3.7628174, -3.24646, 
-3.9605713, -4.4549561, -4.7955322, -4.553833, -5.9710693, -6.1468506), 
lat = c(53.884916, 54.807017, 53.46189, 53.363665, 53.507651, 53.363665, 53.126998, 53.298056,53.884916)), class = "data.frame", row.names = c(NA,-9L))
l<-Line(coords)
sl<-SpatialLines(list(Lines(list(l),ID="a")),proj4string=CRS("+init=epsg:4326"))

Create point

pt<-SpatialPoints(coords[5,]+0.02,proj4string=CRS("+init=epsg:4326"))

Plot

plot(sl)
plot(pt,add=T)

I'm having trouble finding examples of what the next step might be and need help. Example of what distance I would like to calculate Example of what distance I would like to calculate

Upvotes: 1

Views: 2025

Answers (3)

user3857437
user3857437

Reputation: 57

Thankyou to @patL and @Wimpel, I've used your suggestions to come up with a solution to this problem.

First I create spatial lines of set distance and bearings from an origin point using destPoint::geosphere. I then use gIntersection::rgeos to obtain the spatial points where each transect intersects the coastline. Finally I calculate the distance from the origin point to all intersect points for each transect line respectively using gDistance::rgeos and subset the minimum value i.e. the nearest intersect.

load packages

pkgs=c("sp","rgeos","geosphere","rgdal") # list packages
lapply(pkgs,require,character.only=T) # load packages

create data

coastline

coords<-structure(list(lon =c(-6.1468506,-3.7628174,-3.24646, 
-3.9605713,-4.4549561,-4.7955322,-4.553833,-5.9710693,-6.1468506), 
lat=c(53.884916,54.807017,53.46189,53.363665,53.507651,53.363665,53.126998,53.298056,53.884916)), class = "data.frame", row.names = c(NA,-9L))
l=Line(coords)
sl=SpatialLines(list(Lines(list(l),ID="a")),proj4string=CRS("+init=epsg:4326"))

point

sp=SpatialPoints(coords[5,]+0.02,proj4string=CRS("+init=epsg:4326"))
p=coordinates(sp) # needed for destPoint::geosphere

create transect lines

b=seq(0,315,45) # list bearings

tr=list() # container for transect lines

for(i in 1:length(b)){
    tr[[i]]<-SpatialLines(list(Lines(list(Line(list(rbind(p,destPoint(p=p,b=b[i],d=200000))))),ID="a")),proj4string=CRS("+init=epsg:4326")) # create spatial lines 200km to bearing i from origin
    }

calculate distances

minDistance=list() # container for distances


for(j in 1:length(tr)){ # for transect i
    intersects=gIntersection(sl,tr[[j]]) # intersect with coastline
    minDistance[[j]]=min(distGeo(sp,intersects)) # calculate distances and use minimum
}

do.call(rbind,minDistance)

In reality the origin point is a spatial point data frame and this process is looped multiple times for a number of sites. There are also a number of NULL results when carry out the intersect so the loop includes an if statement.

Upvotes: 0

Wimpel
Wimpel

Reputation: 27732

As a heads-up: I'm no hero when it comes to geo-data in R.

Also: I have not automated the calculation for all bearings, but manually performed operations to get the distance to intersect on de 45-bearing.
You will have to figure out the looping by yourself, as I do not have the time. Feel free to provide/post your final findings/code here when you are done.

Here is my crack at this problem, step-by-step.

#load libraries used
library(geosphere)
library(tidyverse)
library(sf)

#get bearings of lines of the polygon
df.poly <- coords %>%
  mutate( lon_next = lead(lon), lat_next = lead(lat) ) %>%
  mutate( bearing_to_next = ifelse( !is.na( lon_next ), 
                                    unlist( pmap( list( a = lon, b = lat, x = lon_next, y = lat_next ),
                                                  ~ round( geosphere::bearing( c(..1, ..2), c(..3, ..4) ) )
                                                  )
                                            ),
                                    NA ) 
          ) %>%
  filter( !is.na( lon_next ) )

#         lon      lat bearing_to_next
# 1 -6.146851 53.88492              56
# 2 -3.762817 54.80702             167
# 3 -3.246460 53.46189            -103
# 4 -3.960571 53.36366             -64
# 5 -4.454956 53.50765            -125
# 6 -4.795532 53.36366             148
# 7 -4.553833 53.12700             -78
# 8 -5.971069 53.29806             -10

#find intersection point based on the intersection of two 'great circles' 
#from two points with a bearing
gcIntersectBearing( 
  #coordinates 2nd point of polyline, with bearing to third point
  c( -3.7628174, 54.807017 ), 167,  
  #coordinates point, with bearing of 45
  c( -4.454956, 53.50765 ), 45 )

#            lon      lat      lon       lat
# [1,] -3.476074 54.07798 176.5239 -54.07798

let's see what we have got so far

p_intersect <- data.frame( lon = -3.476074, lat = 54.07798 ) %>% 
  st_as_sf( coords = c( "lon", "lat" ), crs = 4326 )

startpoint <- coords %>% slice(5) %>% mutate( lon = lon + 0.02, lat = lat + 0.02 ) %>%
  st_as_sf( coords = c("lon","lat"), crs = 4326 )

poly <- coords %>%
  as.matrix() %>%
  list() %>%
  st_polygon() %>%
  st_sfc() %>%
  st_set_crs( 4326 )

mapview::mapview( list(poly, startpoint, p_intersect) )

enter image description here

The location of the intersection point p_intersect on the polygon poly from the startpoint with a 45-degrees bearing looks correct.

Now you can calculate the distance as follows:

#calculate distance
st_distance( startpoint, p_intersect )
# Units: [m]
#         [,1]
# [1,] 87993.3

Google Maps seems to agree on the distance (bit of a margin due to mouseclicking aroung the points, but looks ok to me) enter image description here

Now you will have to figure out some clever looping/vectorisation and you are done :) I have to get back to my real job.

Upvotes: 2

patL
patL

Reputation: 2299

You can use geosphere library to accomplish it. You'll need to add a CRS to your points though:

library(geosphere)

pt <- SpatialPoints(c[5,],
                    proj4string=CRS("+init=epsg:4326")) 

And then use dist2Line function:

st_distance(st_cast(sl, "POINT"), pt)

#     distance       lon      lat ID
#[1,] 2580.843 -4.451901 53.50677  1

Alternatively you can convert your polylines to points using sf package and then get a matrix of distances (you'll need to convert you objects to sfclass):

library(sf)

sl <- SpatialLines(list(Lines(list(l),ID="a")),
                   proj4string=CRS("+init=epsg:4326")) %>% 
  st_as_sf()

pt <- SpatialPoints(coords[5,]+0.02,
                    proj4string=CRS("+init=epsg:4326")) %>% 
  st_as_sf()

st_distance(st_cast(sl, "POINT"), pt)

#Units: [m]
#            [,1]
# [1,] 119833.165
# [2,] 149014.814
# [3,]  79215.071
# [4,]  36422.390
# [5,]   2591.267
# [6,]  30117.701
# [7,]  45287.637
# [8,] 105289.230
# [9,] 119833.165

Upvotes: 3

Related Questions