Search code examples
rshinyshinywidgets

Load countries flags to be displayed in multi.js for many countries in a shiny app


I have the shiny app below in which I create multi.js input with country names and flags. Now vector country works but fos specific countries and names for example de instead of Germany but what if I have a vector like countries2 with different and more country names ?

library(shiny)
library(shinyWidgets)
countries <- c('de', 'br','gr')
countries2 <- c('Germany', 'Brazil','Greece','Italy')

img_urls <- paste0(
  'https://cdn.rawgit.com/lipis/flag-icon-css/master/flags/4x3/',
  countries, '.svg'
)

input_widget <- multiInput(
  inputId = "Id010",
  label = "Countries :", 
  choices = NULL,
  choiceNames = lapply(
    seq_along(countries2), 
    function(i) {
      tagList(
        tags$img(src = img_urls[i], width = 20, height = 15), 
        countries2[i]
      )
    }
  ),
  choiceValues = countries2
)
ui <- fluidPage(
  input_widget
)

server <- function(input, output, session) {
  
}

shinyApp(ui, server)

Solution

  • You can have more country flags by specifying the alpha-2 country codes for them. By adding more alpha-2 country codes in countries and their name in countries2, it should work fine for any country you may want to include.

    There are multiple ways to get the alpha-2 code for each country (eg from here). Below I'll be getting this info from here, for all countries:

    countries_df <- read.csv("https://raw.githubusercontent.com/lukes/ISO-3166-Countries-with-Regional-Codes/master/all/all.csv",strip.white = TRUE)
    countries <- tolower(countries_df[,"alpha.2"])
    countries2 <- countries_df[,"name"]
    

    The reason why this works is because you get the icons for flags from here and the formatting that is used for each country is "alpha-2-code.svg" (eg de.svg for Germany), so in order to get the icons you need these codes instead of just the country names.

    Here's the result combining your code and what I'm saying above. all_countries