9

I'd like to make some style changes to my leaflet map.

Is it possible to include

  • style elements OR
  • a custom path to a css file

either via htmlwidgets for R or LeafletR?

Best

kabr
  • 1,249
  • 1
  • 12
  • 22
  • do you have just a little bit of reproducible code or an example of custom leaflet styling? I think I have an answer, but I do not know. `htmltools` will definitely be your friend here, but there are some other options we can explore using dependencies. – timelyportfolio Mar 02 '16 at 20:37
  • also are you using in `rmarkdown` or not? – timelyportfolio Mar 02 '16 at 20:51
  • no, I don't use rmarkdown. I'd like to use it on a standalone website. – kabr Mar 03 '16 at 06:21

2 Answers2

15

With no code whatsoever in your question, answering is very difficult. I'll attempt an answer. There are two methods of adding custom CSS to an htmlwidget. I will caution up front though that you will need to be very specific or use the !important override, since there is already quite a bit of CSS that is automatically added to leaflet.

Easy but Less Robust

htmlwidgets can be combined with tags from the htmltools package.

library(leaflet)
library(htmltools)

# example from ?leaflet
m = leaflet() %>% addTiles()

# there are two approaches to the custom css problem
#  1.  the easy but less robust way
browsable(
  tagList(list(
    tags$head(
      # you'll need to be very specific
      tags$style("p{font-size:200%;}")
      # could also use url
      #tags$link(href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css",rel="stylesheet")
    ),
    m
  ))
)

More Robust with htmlDependency

You can also use the htmlDependency which will handle conflicts caused by duplicates.

#  2.  you can add dependencies to your leaflet map
#  this mechanism will smartly handle duplicates
#  but carries a little more overhead
str(m$dependencies)  # should be null to start
# 
m$dependencies <- list(
  htmlDependency(
    name = "font-awesome"
    ,version = "4.3.0"
    # if local file use file instead of href below
    #  with an absolute path
    ,src = c(href="http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css")
    ,stylesheet = "font-awesome.min.css"
  )
)

m
timelyportfolio
  • 6,479
  • 30
  • 33
0

I followed timelyportfolio browsable() method, but you will have a small window of the map. To fix this you must add: 100vw and 100vh to leaflet and remove margins from the body.

For example:

library(leaflet)
library(htmltools)

# example from ?leaflet
m = leaflet(height = '100vh', width = '100vw') %>% addTiles()

# there are two approaches to the custom css problem
#  1.  the easy but less robust way
browsable(
  tagList(list(
    tags$head(
      # you'll need to be very specific
      tags$style("p{font-size:200%;} body{margin: 0px;}")
      # could also use url
      #tags$link(href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css",rel="stylesheet")
    ),
    m
  ))
)
ramm
  • 31
  • 4