0

If i've 2 points First one "29.98671,31.21431"

2nd points "29.97864,31.17557"

i put them in Google Maps, get the route between two of them, and i've another one "29.987201, 31.188547" , want to get the nearest point on the road which near to "29.987201, 31.188547".

is there away to do this using R ?help please .

  • 1
    Have a look [here](http://stackoverflow.com/questions/41061718/calculate-decode-and-plot-routes-on-map-using-leaflet-and-r/41066030#41066030) for the route from A to B. the second part is similar - have a look at the osrm `nearest` function. – Christoph Dec 20 '16 at 17:23
  • @Christoph i'm trying to get any information from the question but sry i couldn't, and i installed osrm package but couldn't find the nearest function , but i found `osrmRoute` which gives me the coordinates of road points but can't use it because the first column which is `comm_id` don't know how to get it using my points , this way wont answer my question but will solve half of it , thanks for telling me but is there another way ? – Omar Abd El-Naser Dec 20 '16 at 17:55

1 Answers1

3

1) Get route between two points.

library(ggmap)
# output = 'all' so we get the polyline of the path along the road
my_route <- route(from = "29.98671,31.21431", 
                  to = "29.97864,31.17557",
                  structure = "route", 
                  output = "all")
my_polyline <- my_route$routes[[1]]$legs[[1]]$steps[[1]]$polyline$points

2) Decode polyline to series of points, using function from this linked question

How to decode encoded polylines from OSRM and plotting route geometry?

# DecodeLineR <- function(encoded) {... see linked question ...}
route_points <- DecodeLineR(my_polyline)

3) Plot all the route points, along with our new point

new_point <- data.frame(lat=29.987201, lng=31.188547)

ggplot(route_points, aes(x=lng, y=lat)) + 
  geom_point(shape=21, alpha=0.5) +
  geom_point(data = new_point, color = 'red') +
  coord_quickmap() +
  theme_linedraw()

enter image description here

4) Find which "route point" is closest to the new point

# get each distance in miles (great circle distance in miles)
library(fields)
route_points$distance_to_new <- t(rdist.earth(new_point, route_points))
# it's this one:
route_points[which.min(route_points$distance_to_new), ]

Answer: The 76th point on the poly line is closest, at ~0.19 miles away

        lat      lng distance_to_new
76 29.98688 31.18853      0.01903183
Community
  • 1
  • 1
arvi1000
  • 9,393
  • 2
  • 42
  • 52