我希望在这两点之间添加折线。我怎么能这样做?
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|
答案 0 :(得分:1)
这是我的尝试。由于您想在传单地图上绘制一些路线,因此您希望通过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")
答案 1 :(得分:1)
@ jazzurro的答案是现场的,所以应该仍然是公认的答案。
正如他们所提到的,如果您需要并可以绘制Google地图,您可以在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作者。