Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a scale bar in the R package leaflet?

Tags:

r

leaflet

I have recently discovered the r package “leaflet” and found a great blog with some basic instruction for creating an interactive map (found here) http://mhermans.net/hiking-gpx-r-leaflet.html.

I have not, however been successful at adding a scale bar on the map. That is, I’d like to add a graphic feature that scales distance as you zoom in and out of the map (e.g. a bar at the bottom of the map that represents 1km). The leaflet site (found here) http://leafletjs.com/reference.html#control-scale-l.control.scale discusses this feature: L.control,scale().

Does anyone know how to add a scale bar??

This is the code for my map so far (The “Add Scale Bar” Does NOT work):

# A map of Track data
Mymap <- leaflet() %>% addTiles() %>% 
  addPolylines(data=Dofu1) %>% 
  addPolylines(data=Zak1) %>% 
  addProviderTiles("Esri.WorldImagery")   

# Add a legend 
  Mymap %>% 
    addLegend(position = 'topright', 
              colors = "blue", 
              labels = 'Buruku Tracks', opacity = 0.5,
              title = '')

  # Add a Scale Bar 
  Mymap %>% 
    addControl(Mymap, "Scale", 
            position = c("topright"), 
            layerID = NULL, 
            className = "Scale", 
            data - getMapData(Mymap))
like image 396
Jake1809 Avatar asked Dec 14 '15 17:12

Jake1809


2 Answers

This feature has been added to the development version of the leaflet package. See Add support for scale bar. Also, the second argument to addControl expects html as either a character string or html generated from Shiny or htmltools tags. Finally, I think you have a typo in addControl: data - getMapData(Mymap) should be data = getMapData(Mymap)

like image 194
joeyreid Avatar answered Nov 17 '22 18:11

joeyreid


the scale bar function is implemented and can be added with 'addScaleBar'

leaflet() %>%
  addTiles() %>%
  addScaleBar()
like image 24
Lennert Avatar answered Nov 17 '22 16:11

Lennert