我已经编写了包googleway以使用有效的 API 密钥访问谷歌地图 API。
您可以使用该功能google_directions()
获取路线,包括航点、路线步数、行程、距离、时间等。
例如
library(googleway)
## using a valid Google Maps API key
key <- "your_api_key"
## Using the first and last coordinates as the origin/destination
origin <- c(17.48693, 78.38945)
destination <- c(17.47077, 78.35874)
## and the coordinates in between as waypoints
waypoints <- list(via = c(17.49222, 78.39643),
via = c(17.51965, 78.37835),
via = c(17.49359, 78.40079),
via = c(17.49284, 78.40686))
## use 'stop' in place of 'via' for stopovers
## get the directions from Google Maps API
res <- google_directions(origin = origin,
destination = destination,
waypoints = waypoints,
key = key) ## include simplify = F to return data as JSON
结果是从谷歌地图接收到的所有数据
## see the structure
# str(res)
您在 Google 地图上看到的线路包含在
res$routes$overview_polyline$points
# [1] "slviBqmm}MSLiA{B^wAj@sB}Ac@...
这是一条编码的折线。
要从中获取纬度/经度,请使用该功能decode_pl()
df_polyline <- decode_pl(res$routes$overview_polyline$points)
head(df_polyline)
# lat lon
# 1 17.48698 78.38953
# 2 17.48708 78.38946
# 3 17.48745 78.39008
# 4 17.48729 78.39052
# 5 17.48707 78.39110
# 6 17.48754 78.39128
当然,您可以根据需要进行绘图
library(leaflet)
leaflet() %>%
addTiles() %>%
addPolylines(data = df_polyline, lat = ~lat, lng = ~lon)
编辑 2017-07-21
从googleway
2.0 开始,您可以在 Google 地图中绘制折线,或者像以前一样使用解码的坐标,或者直接使用折线
google_map(key = key) %>%
add_polylines(data = data.frame(polyline = res$routes$overview_polyline$points),
polyline = "polyline")