3

How can the font of scale bar be modified in leaflet? Example below of what I have tried without success:

 library(leaflet)
    library(htmltools)
    
    # Create a basic Leaflet map
    map <- leaflet() %>%
      addTiles() %>%
      setView(lng = -121.2722, lat = 38.1341, zoom = 10)  
    
    # Add a scale bar to the map
    map <- map %>%
      addScaleBar() %>% 
      onRender("
function(el, x) {
  var map = this;
L.control.scale({
    position: 'bottomleft',
    imperial: false,
    onRender: function(options) {
        var scaleContainer = this._container;
        scaleContainer.style.fontSize = '30px' !important; 
    }
}).addTo(map);
}
")  
map

1 Answer 1

1

With addScaleBar() you already added a scale bar to the map. To edit it, you can use onRender to execute JavaScript after the map-widget is displayed. Then within the JS-Code, first query select all instances of the scale-divs (4) first out

and then apply the style attribute via scaleDiv.style.fontSize = '30px'; via JS' for-loop structure forEach: it iterates of each element of the .. Each element inside the loop is then called scaleDiv and you can do whatever you want to this div. E.g. use the dot-notation to set the .style.fontSize of the current iterator scaleDiv.

library(leaflet)
library(htmlwidgets)

# Create a basic Leaflet map
leaflet() %>%
  addTiles() %>%
  setView(lng = -121.2722, lat = 38.1341, zoom = 10)  %>%
  addScaleBar() %>% 
  onRender("
function(el, x) {
  document.querySelectorAll('div.leaflet-control-scale-line').forEach(scaleDiv => {
     scaleDiv.style.fontSize = '30px'; // adjust size
  });
}
")

Notes that is, you maybe should not set it so high because it will not be readable. You could also set the width, but I guess that defeats the purpose of a scale bar.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.