OK I have been able to integrate maps into Shinny, but always when I use the pipe operator. This time I have a map that has a for loop and as I am new to R, I didn't know how to use the pipe operator in that case.
The leaflet map is as follows:
libraries used:
library(data.table)
library(leaflet)
library(shiny)
data.table:
lat<-c(40.41766, 40.43305 ,40.43687, 40.39563, 40.39088, 40.39215, 40.39458, 40.40451, 40.40627, 40.40864)
lng<-c(-3.701328, -3.709352, -3.708531, -3.736556, -3.734796, -3.741867, -3.741222, -3.705399, -3.710980, -3.710310)
colors<-c("#3D00FFFF","#52FF00FF","#3D00FFFF","#0052FFFF","#52FF00FF","#52FF00FF","#52FF00FF","#0052FFFF","#3D00FFFF","#0052FFFF")
name<-as.factor(c("Rafa","Luis","Rafa","Belen","Luis","Luis","Luis","Belen","Rafa","Belen"))
hour_range<-c("Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours","Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours","Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours","Morning_Working_Hours")
data<- data.table(name,lat,lng,hour_range,colors)
leaflet map:
map<- leaflet(data)
map<- addTiles(map)
for( name in unique(data$name)){
map<- addPolylines(map, lng=~lng,lat=~lat,data=data[data$name==name & data$hour_range=="Morning_rush_hours",],color=~colors)
map<-addPolylines(map, lng=~lng,lat=~lat,data=data[data$name==name & data$hour_range=="Sleeping_Hours",],color=~colors)
}
map
This map works fine the problem is that I don't know how to integrate it with shinny, cause I am not using pipes. And it appears me an error called:
Argument "map" is missing with no default. Because Shiny doesn't see my map.
Try the following example. And also try to run it, when you uncomment the last call to my_map
in renderLeaflet
. This is the return value of the function and if you dont call it, nothing will happen.
library(shiny)
library(leaflet)
data = data.frame(
lng = runif(100,15,16),
lat = runif(100,45,50)
)
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
my_map <- leaflet(data)
my_map <- addTiles(map = my_map)
for (i in 1:3) {
my_map <- addCircleMarkers(map = my_map, lat = ~lat, lng = ~lng)
my_map <- addCircleMarkers(map = my_map, lat = ~lat * i/10, lng = ~lng * i/10, color ="red")
my_map <- addCircleMarkers(map = my_map, lat = ~lat * i/30, lng = ~lng * i/30, color ="green")
}
## Uncomment the next line, to see whats happening.
my_map
})
}
shinyApp(ui, server)