2017-02-22 81 views
2

我正在研究R中的自定义路由规划器。我正在使用Google Maps Directions API的输出。我想在两个地方之间的地图上显示路线。到目前为止,一切都很顺利。唯一的问题是,我现在不知道如何根据速度给出多种颜色的路线。我在网上搜索了几天,找不到符合我目标的东西。这就是我发布这篇文章的原因。如何绘制R中多种颜色的多义线?

#install.packages("leaflet") 
library(leaflet) 


pal <- colorNumeric(
palette = unique(polyline$Col), 
domain = polyline$Speed, 
na.color = "#FFFFFF" 
) 
rm(map) 
map <- leaflet() 
map <- addTiles(map) 
a <- 1 
for(a in length(unique(polyline$Step_ID))){ 


map <- addPolylines(map,lng = polyline$Lon, 
      lat = polyline$Lat, 
      data = polyline[polyline$Step_ID==a,], 
      color = polyline$col) 
a <- a + 1 
} 
map <- addLegend(map,"bottomright", pal = pal, values = polyline$Speed, 
     title = "Speed", 
     opacity = 1) 
map 

到目前为止,我认为你必须创建多个折线(纠正我,如果我错了)来绘制多种颜色:

This is how my polyline data frame looks like:

然后我用TE下面的代码显现它Leafet在路线中。这就是为什么我做了一个for循环,将PolyLine添加到地图中。

This is how my visualization looks like

寄托都只是怎么想的那样。唯一的问题是线的着色。我想像Google一样对流量着色。

有人可以帮我解决这个问题吗?

+1

可以输入您的数据集 –

+0

.Label = c(“red”,“orange”,“green”),class =“factor”)),.Names = c(“Step_ID”, “Dist_Value” ,“Dist_Text”,“Dur_Text”,“Dur_Value”,“Lat”,“Lon”, “Speed”,“Col”),row.names = c(NA,1448L),class =“data.frame”) –

回答

1

要完全复制您的问题,您需要向我们提供polyline的实际数据(即不是截图)。在此之前,我将创建自己的数据集并向您展示如何创建彩色线条。

而且,正如你使用谷歌的API来获取方向,我假设你有一个API密钥,所以我要告诉你如何使用我的googleway包做

library(googleway) 

api_key <- "your_api_key" 

directions <- google_directions(origin = "St Kilda, Melbourne, Australia", 
           destination = "Geelong, Victoria, Australia", 
           key = api_key) 

## the results of the API give you distance in metres, and time in seconds 
## so we need to calculate teh speed 
spd <- (directions$routes$legs[[1]]$steps[[1]]$distance$value/1000)/(directions$routes$legs[[1]]$steps[[1]]$duration$value/ 60/60) 

## then we can start to build the object to use in the plot 
## and as we are staying within Google's API, we can use the encoded polyline to plot the routes 
## rather than extracting the coordinates 
df <- data.frame(speed = spd, 
       polyline = directions$routes$legs[[1]]$steps[[1]]$polyline) 



df$floorSpeed <- floor(df$speed) 
colours <- seq(1, floor(max(df$speed))) 
colours <- colorRampPalette(c("red", "yellow","green"))(length(colours)) 

df <- merge(df, 
      data.frame(speed = 1:length(colours), 
         colour = colours), 
      by.x = "floorSpeed", 
      by.y = "speed") 

map_key <- "your_map_api_key" 

google_map(key = map_key) %>% 
    add_polylines(data = df, polyline = "points", stroke_colour = "colour", 
        stroke_weight = 5, stroke_opacity = 0.9) 

enter image description here

制作路线规划中闪亮的一种方式见this answer

+0

哎呀抱歉!我是新来的网站。 谢谢,这对我有用!它只适用于我的个人Mac,而不适用于我实习的Windows电脑。有点奇怪。但我会弄清楚是什么问题。但感谢您的帮助和包装! –

+0

@DaveMeijdam - 在Windows上安装软件包或查看地图时是否存在问题? – SymbolixAU

+0

当我运行'devtools :: install_github(“SymbolixAU/googleway”)'时,它不会给出任何错误。但是当我运行绘制地图的代码时,它没有显示任何东西。观众保持空白。 –