我希望在这两点之间添加折线。我怎样才能做到这一点?
m <- leaflet() %>%
addPolylines() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng = -87.6266382, lat = 41.8674336,
popup = "starting") %>%
addMarkers(lng = -87.64847, lat = 41.9168862,
popup = "Destination")
m # Print the map
数据示例。
| region | from_lat | from_long | to_lat | to_long |
|-------------|------------|------------- |-------------|----------- |
| 1 | 41.8674336 | -87.6266382 | 41.887544 | -87.626487 |
| 2 | 41.8674336 | -87.6266382 | 41.9168862 | -87.64847 |
| 3 | 41.8674336 | -87.6266382 | 41.8190937 | -87.6230967|
这是我的尝试。由于您想在传单地图上绘制一些路线,因此您希望通过googleway
包实现此任务。它允许您使用google_directions()
和decode_pl()
提取路径数据。由于您有多个路由,因此您希望使用lapply()
并创建数据集。获得路线数据后,您的工作就很简单;你使用addPolylines()
中的数据。
library(dplyr)
library(googleway)
library(leaflet)
mydf <- data.frame(region = 1:3,
from_lat = 41.8674336,
from_long = -87.6266382,
to_lat = c(41.887544, 41.9168862, 41.8190937),
to_long = c(-87.626487, -87.64847, -87.6230967))
mykey <- "you need to have your API key here"
lapply(1:nrow(mydf), function(x){
foo <- google_directions(origin = unlist(mydf[x, 2:3]),
destination = unlist(mydf[x, 4:5]),
key = mykey,
mode = "driving",
simplify = TRUE)
pl <- decode_pl(foo$routes$overview_polyline$points)
return(pl)
}
) %>%
bind_rows(.id = "region") -> temp
m <- leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
addPolylines(data = temp, lng = ~lon, lat = ~lat, group = ~region) %>%
addMarkers(lng = -87.6266382, lat = 41.8674336,
popup = "starting")%>%
addMarkers(data = mydf, lng = ~to_long, lat = ~to_lat,
popup = "Destination")
@ jazzurro的答案是现场的,所以应该仍然是公认的答案。
正如他们所提到的,如果你想要并绘制谷歌地图,你可以在googleway
包中完成所有这些。使用传单的主要区别在于您不需要解码折线,Google Map可以为您处理编码的字符串。
polylines <- lapply(1:nrow(mydf), function(x){
foo <- google_directions(origin = unlist(mydf[x, 2:3]),
destination = unlist(mydf[x, 4:5]),
key = apiKey,
mode = "driving",
simplify = TRUE)
## no need to decode the line, just return the string as-is
foo$routes$overview_polyline$points
}
)
df <- data.frame(polylines = unlist(polylines), stringsAsFactors = F)
## add some colour values for the markers
mydf$colour_from <- "red"
mydf$colour_to <- "blue"
## plot the polylines and the markers
google_map(key = mapKey) %>%
add_markers(data = mydf, lat = "from_lat", lon = "from_long", colour = "colour_from") %>%
add_markers(data = mydf, lat = "to_lat", lon = "to_long", colour = "colour_to") %>%
add_polylines(data = df, polyline = "polylines")
注意:我是googleway作者。