在谷歌地图中最接近给定点的道路上获取点

时间:2016-12-20 17:16:09

标签: r

如果我有2分 第一个" 29.98671,31.21431"

第二点" 29.97864,31.17557"

我把它们放在Google地图上,获取其中两个之间的路线,然后我又来了另一个" 29.987201,31.188547" ,想要在靠近" 29.987201,31.188547"的道路上得到最近的点。

请使用R?帮助做到这一点。

1 个答案:

答案 0 :(得分:3)

1)获取两点之间的路线。

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)使用此链接问题的函数

将折线解码为一系列点

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

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

3)绘制所有路线点以及我们的新点

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)找出哪个“路线点”最接近新点

# 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), ]

答案:多边形线上的第76个点最接近,距离大约0.19英里

        lat      lng distance_to_new
76 29.98688 31.18853      0.01903183