rr-leafletmapview

how to draw a compass on leaflet or mapview map


How can I add a compass control to my map? There used to be a function called addControlCompass in leaflet.extras I believe but is not there anymore. Does anyone know how to add a compass or an arrow indicating north up?

library(leaflet)
library(leaflet.extras)

# Create a basic Leaflet map
map <- leaflet() %>%
  addTiles() %>%
  setView(lng = -121.2722, lat = 38.1341, zoom = 10)  

# Add a scale bar and compass to the map
map <- map %>%
  addScaleBar(position = "bottomleft", options = scaleBarOptions(maxWidth = 100, metric = TRUE, imperial = FALSE)) %>%
  addControlCompass(position = "topright", options = compassOptions())
  map

Solution

  • If you just need an arrow pointing north, you can use some HTML + CSS and add it to the map using htmltools. You can take any arrow design and paste it inside the div.

    out

    library(leaflet)
    library(htmltools) 
    
    north_arrow <- HTML('
    <div style="
        width: 20px;
        height: 30px;
        text-align: center;
        font-weight: bold;
        font-size: 22px;
    ">
        <div>⮙</div> <!-- add arrow UTF8 symbol here -->
        <div>N</div>
    </div>')
    
    leaflet() %>%
      addTiles() %>%
      setView(lng = -121.2722, lat = 38.1341, zoom = 10) %>%
      addScaleBar(position = "bottomleft", options = scaleBarOptions(maxWidth = 100, metric = TRUE, imperial = FALSE)) %>%
      addControl(north_arrow, position = "topright")
    

    Or a bit more fancy

    library(leaflet)
    library(htmltools) 
    
    
    map <- leaflet() %>%
      addTiles() %>%
      setView(lng = -121.2722, lat = 38.1341, zoom = 10) %>%
      addScaleBar(position = "bottomleft", options = scaleBarOptions(maxWidth = 100, metric = TRUE, imperial = FALSE)) %>%
      addControl(HTML('
    <div style="width: 90px;height: 90px;">
        <img src="https://clipart-library.com/images/rTnRjnAGc.png" style="width: 100%; width: 100%; opacity: 0.7;">
    </div>'), position = "topright", className = "leaflet-control-nobg")
    
    map <- htmlwidgets::prependContent(map, 
                                       tags$style(".leaflet-control-nobg { background: none !important; box-shadow: none !important; border: none !important; }")
    )
    
    map
    

    out