Leaflet map doesn't render using shinydasboard

Hello!! I'm having issues rendering my leaflet map in a shiny dashboard. There are no errors in my code but the tab box where the map was supposed to be is not rendered. The tab box keeps in blank.

When I run the app locally it works perfectly, and the tiles of the map are rendered. However, running on the server does not seem to work as locally it does. Does anyone know what is happening?? I have searched in similar topics but there is not a solution that works for me. This is the URL of the app:http://vvalin.shinyapps.io/SoCyL

Thank you :slightly_smiling_face:
Victor Valin

Sorry about your issue. I know leaflet usually has no issues with shinyapps.io (I have a few apps that rely on it). A good way to diagnose the issue, and to pose this question in a way others are more likely to be able to help, is to share your code in a minimum example that reproduces this issue.

Ohh! Thank youu for the respons. That makes sense. Here is my code:

Ui

#create the header of the Shiny Dashboard
header <- dashboardHeader(
title=strong("Buscador de entidades de voluntariado en Castilla y León", style="font-family: 'Tahoma'; font-size: 30px;", img(src="pin.png",height=40)), #add title with a map icon
titleWidth = 900)

#create sidebard of Shiny Dashboard
sidebar <- dashboardSidebar(
sidebarMenu(id="tabs",menuItem(strong("Mapa interactivo"), #strong indicates bolded
tabName="Map", icon = icon("map-marker"))

)
)

body<-dashboardBody(
tabItems(tabItem("Map",
tags$style(type = "text/css", #specify font type and size for the dashboard body for the map tab
"label { font-size: 16px; }", #all labels are 16 pixel font
".selectize-input { font-size: 16px;} ", #the titles of the text inputs and drop-down menus are 16 pixels
".selectize-dropdown { font-size: 16px; }",
"#Municipio { font-size: 16px; }", #increase the size of the city and address labels on the text input
"#Dirección { font-size: 16px; }",
"#Provincia { font-size: 16px; }"
),

               #create columns
               fluidRow(
                 column(width = 8, HTML("<div style='height: 600px;'>"), #set height of the box the map is in so that it lines up with the right-hand boxes
                        p("Por favor espere hasta que el mapa se actualice.", style="color:grey; font-size:10pt"), #add a notification above the map 
                        box(width = NULL, status="success", solidHeader = TRUE, title="Mapa de Castilla y León", #create a green box that has the map
                            leafletOutput("map2", height=940)), #show map in this box
                        HTML("</div>") #add some space at the bottom of the map
                 ),
                 
                 column(width=4,style='padding:0px;', #add padding so that the title of this box lines up with the map
                        h3(strong("Explorar entidades en función de su naturaleza")), #add bolded title to this column
                        p("Haz click sobre cada marcador para obtener información extra", style="font-size:12pt"), 
                        
                        box(width=NULL, status="warning", #add red box that includes a drop-down menus for specialty (changes markers on map)
                            selectInput("specialty", h4(strong("Naturaleza:")), c("ASOCIACION","FUNDACION","INSTITUCIONES, ORDENES, CONGREGACIONES RELIGIOSAS Y SIMILARES",
                                                                                  "FEDERACION-CONFEDERACION", "ADMINISTRACION LOCAL", "PATRONATO DE ENTIDADES SIN FIN DE LUCRO PUBLICAS",
                                                                                  "SOCIEDADES","ADMINISTRACION AUTONOMICA"))),
                        
                        h3(strong("Explorar entidades en función de su localización aproximada")),
                        
                        box(width=NULL, status="warning", 
                            selectInput("Provincia", h4(strong("Provincia:")), choices = sort(Voluntariado$Provincia))),
                        box(width=NULL, status="warning", 
                            selectInput("Localidad", h4(strong("Localidad:")), choices = sort(Voluntariado$Localidad))),
                        
                        
                        
                        h3(strong("Explorar entidades por localización exacta")), #add a title for the next box
                        
                        box(width=NULL, status = "primary", 
                            selectInput("address",h4(strong("Dirección")),choices = sort(Voluntariado$Dirección)), #the user inputs address
                            p(em("Ejemplo: CALLE LOPE DE VEGA 1, 47010, VALLADOLID	", style="color:red; font-size:12pt"))))), #add a notification that is italicized indicating an example address in Birmingham, AL
               
               
               
               fluidRow(
                 column(width=2,offset = 8,
                        box(width=NULL, status="info", actionButton("geocode", h4(strong("Búsqueda"))))), #add a button that the user pushes to geocode inputted address and draws a circle
                 column(width=2, offset = 8,
                        box (width=NULL, status="danger", actionButton("clear", h4(strong("Limpiar"))))) #add a button to clear the geocoded address and circle
                 
               )

)
))

ui<-dashboardPage(header, #put entired dashboard together
sidebar,
body)

The server part I think could make the error:

Server<-function(input, output, session) {

icons <- awesomeIcons(
icon = 'ios-close',
iconColor = "black",
library = 'ion')

output$map2<- renderLeaflet({leaflet() %>% addTiles(urlTemplate = "//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
options = tileOptions(minZoom=7, maxZoom=16)) %>%
setView(lng=-4.7286749, lat=41.6524094,zoom = 7)%>%
addPolygons(data = limites ,fillColor = "green")})

Hope someone can help me with this issue! Thank you

Please provide a sample of your dataframes: Voluntariado and limites

e.g. paste the output from dput(Voluntariado)

Anyway, this works for me:


library(shinydashboard)
library(leaflet)

Voluntariado <- data.frame(Provincia = "Waikato", Localidad = "Hamilton", Dirección = "North")

# create the header of the Shiny Dashboard
header <- dashboardHeader(
  title = strong("Buscador de entidades de voluntariado en Castilla y León", style = "font-family: 'Tahoma'; font-size: 30px;", img(src = "pin.png", height = 40)), # add title with a map icon
  titleWidth = 900
)

# create sidebard of Shiny Dashboard
sidebar <- dashboardSidebar(
  sidebarMenu(id = "tabs", menuItem(strong("Mapa interactivo"), # strong indicates bolded
    tabName = "Map", icon = icon("map-marker")
  ))
)

body <- dashboardBody(
  tabItems(tabItem(
    "Map",
    tags$style(
      type = "text/css", # specify font type and size for the dashboard body for the map tab
      "label { font-size: 16px; }", # all labels are 16 pixel font
      ".selectize-input { font-size: 16px;} ", # the titles of the text inputs and drop-down menus are 16 pixels
      ".selectize-dropdown { font-size: 16px; }",
      "#Municipio { font-size: 16px; }", # increase the size of the city and address labels on the text input
      "#Dirección { font-size: 16px; }",
      "#Provincia { font-size: 16px; }"
    ),

    # create columns
    fluidRow(
      column(
        width = 8, HTML("<div style='height: 600px;'>"), # set height of the box the map is in so that it lines up with the right-hand boxes
        p("Por favor espere hasta que el mapa se actualice.", style = "color:grey; font-size:10pt"), # add a notification above the map
        box(
          width = NULL, status = "success", solidHeader = TRUE, title = "Mapa de Castilla y León", # create a green box that has the map
          leafletOutput("map2", height = 940)
        ), # show map in this box
        HTML("</div>") # add some space at the bottom of the map
      ),

      column(
        width = 4, style = "padding:0px;", # add padding so that the title of this box lines up with the map
        h3(strong("Explorar entidades en función de su naturaleza")), # add bolded title to this column
        p("Haz click sobre cada marcador para obtener información extra", style = "font-size:12pt"),

        box(
          width = NULL, status = "warning", # add red box that includes a drop-down menus for specialty (changes markers on map)
          selectInput("specialty", h4(strong("Naturaleza:")), c(
            "ASOCIACION", "FUNDACION", "INSTITUCIONES, ORDENES, CONGREGACIONES RELIGIOSAS Y SIMILARES",
            "FEDERACION-CONFEDERACION", "ADMINISTRACION LOCAL", "PATRONATO DE ENTIDADES SIN FIN DE LUCRO PUBLICAS",
            "SOCIEDADES", "ADMINISTRACION AUTONOMICA"
          ))
        ),

        h3(strong("Explorar entidades en función de su localización aproximada")),

        box(
          width = NULL, status = "warning",
          selectInput("Provincia", h4(strong("Provincia:")), choices = sort(Voluntariado$Provincia))
        ),
        box(
          width = NULL, status = "warning",
          selectInput("Localidad", h4(strong("Localidad:")), choices = sort(Voluntariado$Localidad))
        ),



        h3(strong("Explorar entidades por localización exacta")), # add a title for the next box

        box(
          width = NULL, status = "primary",
          selectInput("address", h4(strong("Dirección")), choices = sort(Voluntariado$Dirección)), # the user inputs address
          p(em("Ejemplo: CALLE LOPE DE VEGA 1, 47010, VALLADOLID	", style = "color:red; font-size:12pt"))
        )
      )
    ), # add a notification that is italicized indicating an example address in Birmingham, AL

    fluidRow(
      column(
        width = 2, offset = 8,
        box(width = NULL, status = "info", actionButton("geocode", h4(strong("Búsqueda"))))
      ), # add a button that the user pushes to geocode inputted address and draws a circle
      column(
        width = 2, offset = 8,
        box(width = NULL, status = "danger", actionButton("clear", h4(strong("Limpiar"))))
      ) # add a button to clear the geocoded address and circle
    )
  ))
)

ui <- dashboardPage(
  header, # put entired dashboard together
  sidebar,
  body
)

Server <- function(input, output, session) {

  icons <- awesomeIcons(
    icon = "ios-close",
    iconColor = "black",
    library = "ion"
  )

  output$map2 <- renderLeaflet({
    leaflet() %>%
      addTiles(
        urlTemplate = "//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        options = tileOptions(minZoom = 7, maxZoom = 16)
      ) %>%
      setView(lng = -4.7286749, lat = 41.6524094, zoom = 7)
    # %>%
    #   addPolygons(data = limites, fillColor = "green")
  })
}

shinyApp(ui, Server)
1 Like

Thank you for your response @woodward. My problem is when I deploy the app into Shinyapps.io because the app runs perfectly in my computer. I run it again as you said, but the problem is still happening.
Have you tried to deploy it on shinyapps.io?

Anyway, here is my data. Voluntariado is a csv that contains information about non-profit organization and limites is the shapefile to use with the function addPolygons.

head(Voluntariado)
X Nº.Registro
1 1 A-0012
2 2 A-0014
3 3 A-0016
4 4 A-0017
5 5 A-0021
6 6 A-0025
Denominación
1 ASOCIACION COYANTINA DE VOLUNTARIADO (ACOVOL)
2 ASOCIACION RED MADRE BURGOS
3 ASOCIACION DE FAMILIARES DE ENFERMOS DE ALZHEIMER Y PROBLEMAS NEUROLOGICOS DERIVADOS DE LA EDAD - AFAMER
4 ASOCIACION DE FAMILIARES DE ENFERMOS DE ALZHEIMER DE SEGOVIA
5 CAJA DE BURGOS FUNDACION BANCARIA
6 FEDERACION PROVINCIAL DE PENSIONISTAS Y JUBILADOS DE VALLADOLID
Fecha.última.modificación
1 2015-07-05
2 2015-07-05
3 2019-05-16
4 2017-09-18
5 2016-07-04
6 2017-09-18
Dirección
1 CALLE SAN MIGUEL 16, 24200, VALENCIA DE DON JUAN
2 CALLE VICTORIA BALFE 12-2º A, 9006, BURGOS
3 CALLE ALEJANDRO RODRIGUEZ DE VALCARCEL 12-BAJO, 9550, VILLARCAYO
4 CALLE ANDRES REGUERA ANTON S/N - Centro Integral de Servicios Sociales de la Albuera, 40004, SEGOVIA
5 PLAZA DE LA LIBERTAD S/Nº, 9004, BURGOS
6 CALLE OLMEDO 5, 47013, VALLADOLID
Código.Postal Localidad Provincia Teléfono Email
1 24200 VALENCIA DE DON JUAN LEON 652953465
2 9006 BURGOS BURGOS 617909312 burgos@redmadre.es
3 9550 VILLARCAYO BURGOS 947130450
4 40004 SEGOVIA SEGOVIA 921431678 alzheimersg@gmail.com
5 9004 BURGOS BURGOS 947258113 obrasocial@cajadeburgos.es
6 47013 VALLADOLID VALLADOLID 983236678 fedva@telefonica.net
Web Naturaleza
1 ASOCIACIÓN
2 www.redmadre.es ASOCIACIÓN
3 ASOCIACIÓN
4 www.alzheimersegovia.com ASOCIACIÓN
5 www.medioambientecajadeburgos.com FUNDACIÓN
6 FEDERACIÓN-CONFEDERACIÓN
Ámbito.sectorial
1 ACCION SOCIAL Y SERVICIOS SOCIALES
2 ACCION SOCIAL Y SERVICIOS SOCIALES, FOMENTO DEL VOLUNTARIADO, SANITARIAS
3 ACCION SOCIAL Y SERVICIOS SOCIALES
4 ACCION SOCIAL Y SERVICIOS SOCIALES
5 DEFENSA Y PROTECCION DEL MEDIO AMBIENTE
6 ACCION SOCIAL Y SERVICIOS SOCIALES, FOMENTO DEL VOLUNTARIADO
Destinatarios
1 EXCLUSION SOCIAL, [PERSONAS INMIGRANTES, REFUGIADAS Y ASILADAS], INFANCIA, PERSONAS MAYORES, POBLACIÓN GENERAL
2 (MUJER)
3 PERSONAS MAYORES
4 PERSONAS MAYORES
5 POBLACIÓN GENERAL
6 PERSONAS MAYORES
lon Latitud address
1 -5.516066 42.29370 calle san miguel, 16, 24200 valencia de don juan, león, spain
2 -3.681067 42.36018 calle victoria balfe, 12, 2º, 09006 burgos, spain
3 -3.575091 42.93742 calle alejandro rodríguez de valcárcel, 12, bajo, 9550, 09550 villarcayo, burgos, spain
4 -4.104331 40.94511 calle andrés reguera antón, s/n, 40004 segovia, spain
5 -3.699236 42.34161 plaza de la libertad, 4, 09004 burgos, spain
6 -4.720413 41.63903 calle olmedo, 5, 47013 valladolid, spain

limites@data
cod_ine_pro provincia
0 9 Burgos
1 34 Palencia
2 42 Soria
3 47 Valladolid
4 49 Zamora
5 5 Avila
6 24 Leon
7 40 Segovia
8 37 Salamanca

Any idea?

Can you post the output from dput(Voluntariado) and dput(limites) instead of the way that you have done it?

My problem is when I deploy the app into Shinyapps.iobecause the app runs perfectly in my computer.

How are you loading the packages? It could be that. For example, pacman::p_load() doesnt work with shinyapps.io but library() does.

I dont't use > pacman::p_load(). I am only loading the packages with > library(). Anyway, this is my > global.R:

Antes de nada, limpiamos el workspace, por si hubiera algún dataset o información cargada

rm(list = ls())

Limpiamos la consola

cat("\014")

Cambiar el directorio de trabajo

getwd()

#load the necessary packages
library(shiny)
library(shinydashboard)
library(leaflet)
library(rgeos)
library(rgdal)
library(ggmap)
library(shinyjs)
library(rsconnect)
library(tidyverse)
library(rstudioapi)

Voluntariado<-read.csv("./Voluntariado.csv",
sep = ",", encoding = "latin1")

#Filtramos solo CyL
Voluntariado<- Voluntariado %>%
filter(!Provincia=="MADRID")

Voluntariado<-Voluntariado%>%
filter(!Provincia=="MURCIA")

Voluntariado<-Voluntariado%>%
filter(!Provincia=="VIZCAYA")

Voluntariado<-Voluntariado %>%
filter(!Web=="www.seo.org")

Voluntariado<-Voluntariado%>%
filter(!Email=="caricuca@hotmail.com")

Formateamos la variable dirección

Voluntariado$Dirección<-paste0(Voluntariado$Dirección, sep=", ",
Voluntariado$Código.Postal, sep=", ",
Voluntariado$Localidad)

Eliminamos espacios de numeros tfno

Voluntariado$Teléfono<-gsub("\s","",Voluntariado$Teléfono)

Moldeamos el archivo polígono para implementar los límites provinciales

limites<-readOGR(dsn = getwd(), layer = "limites-provinciales-de-castilla-y-leon-recintos",
encoding = "UTF-8")
limites@data

limites$provincia[limites$provincia %in% c("�vila")] <- "Avila"
limites$provincia[limites$provincia %in% c("Le�n")] <- "Leon"
limites@data

Filtramos por naturaleza de la entidad

ASOCIACION<-Voluntariado %>% dplyr::filter(Naturaleza=="ASOCIACIÓN")
FUNDACION<-Voluntariado %>% dplyr::filter(Naturaleza=="FUNDACIÓN")
INSTITUCIONES<-Voluntariado%>% dplyr::filter(Naturaleza=="INSTITUCIONES, ÓRDENES, CONGREGACIONES RELIGIOSAS Y SIMILARES")
FEDERACION<-Voluntariado%>% dplyr::filter(Naturaleza=="FEDERACIÓN-CONFEDERACIÓN")
ADMINISTRACION_L<-Voluntariado%>% dplyr::filter(Naturaleza=="ADMINISTRACIÓN LOCAL")
PATRONATO<-Voluntariado%>% dplyr::filter(Naturaleza=="PATRONATO DE ENTIDADES SIN FIN DE LUCRO PÚBLICAS")
SOCIEDADES<-Voluntariado%>% dplyr::filter(Naturaleza=="SOCIEDADES")
ADMINISTRACION_A<-Voluntariado%>% dplyr::filter(Naturaleza=="ADMINISTRACIÓN AUTONÓMICA")

Any idea of something that could be wrong?

Hey! Thank you for reply. I did what you said. These are the outputs:

dput(Voluntariado[1:2,])
structure(list(X = 1:2,
Nº.Registro = c("A-0012", "A-0014"),
Denominación = c("ASOCIACION COYANTINA DE VOLUNTARIADO (ACOVOL)",
"ASOCIACION RED MADRE BURGOS"),
Fecha.última.modificación = c("2015-07-05",
"2015-07-05"),
Dirección = c("CALLE SAN MIGUEL 16, 24200, VALENCIA DE DON JUAN",
"CALLE VICTORIA BALFE 12-2º A, 9006, BURGOS"),
Código.Postal = c(24200L,
9006L), Localidad = c("VALENCIA DE DON JUAN", "BURGOS"),
Provincia = c("LEON", "BURGOS"),
Teléfono = c("652953465",
"617909312"),
Email = c("", "burgos@redmadre.es"),
Web = c("",
"www.redmadre.es"),
Naturaleza = c("ASOCIACIÓN", "ASOCIACIÓN"
),
Ámbito.sectorial = c("ACCION SOCIAL Y SERVICIOS SOCIALES",
"ACCION SOCIAL Y SERVICIOS SOCIALES, FOMENTO DEL VOLUNTARIADO, SANITARIAS"
),
Destinatarios = c("EXCLUSION SOCIAL, [PERSONAS INMIGRANTES, REFUGIADAS Y ASILADAS], INFANCIA, PERSONAS MAYORES, POBLACIÓN GENERAL",
"(MUJER)"),
lon = c(-5.5160663, -3.6810673),
Latitud = c(42.2937037,
42.3601758),
address = c("calle san miguel, 16, 24200 valencia de don juan, león, spain",
"calle victoria balfe, 12, 2º, 09006 burgos, spain")), row.names = 1:2, class = "data.frame")

dput(limites@data)
structure(list(cod_ine_pro = c(9, 34, 42, 47, 49, 5, 24, 40,
37),
provincia = c("Burgos", "Palencia", "Soria", "Valladolid",
"Zamora", "Avila", "Leon", "Segovia", "Salamanca")), row.names = 0:8, class = "data.frame")

Might the data cause the problem??