I have a leaflet map with a polyline. I would like to give the polyline a color gradient from the beginning of line to the end of line. The color will not be dependent on any other variables. The line represents a trajectory, so I would like to make the direction of the trajectory visible with colors.
I have tried numerous things, but nothing is working.
The polyline is from a Line dataset (S4 object of class Line) that contains the coordinates under the name 'coords'. You can see the structure of it below:
This code works for the polyline with just one color:
map <- leaflet(data=longlatcoor)
map <- addTiles(map)
map <- addCircles(map, data=longlatcoor, radius=2)
sl1 = Line(longlatcoor)
map <- addPolylines(map,data=sl1, color = "green")
map
The longlatcoor is a SpatialPoints dataset. I cannot get a gradient color on the polyline, no matter what I do.
I am new to R and I struggle to understand the error messages and what else I can do.
I tried this (code is copied from another site, except the name of my sl1 dataset):
gradientFunction <- colorRampPalette(c("white", "blue"))
colorGradient <- gradientFunction(dim(df)[1])
df1 <- sl1 %>%
mutate(nextLat = lead(lat),
nextLng = lead(lng),
color = colorGradient
)
gradient_map <- leaflet() %>%
addTiles()
for (i in 1:nrow(df1)) {
gradient_map <- addPolylines(map = gradient_map,
data = df1,
lng = as.numeric(df1[i, c('lng', 'nextLng')]),
lat = as.numeric(df1[i, c('lat', 'nextLat')]),
color = as.character(df1[i, c('color')])
)
}
gradient_map
But I get this error when I try to create df1: no applicable method for 'mutate' applied to an object of class "Line"
I have also tried this:
pal <- colorNumeric(
palette = "Blues",
domain = sl1@coords)
leaflet() %>%
addTiles() %>%
addPolylines(data = df, lng = ~lng, lat = ~lat,
color = ~pal(coords))
but get this error:
no applicable method for 'metaData' applied to an object of class "function"