rr-leaflet

How to add label to inset using addMiniMap in leaflet


I can add labels to the main leaflet window but can't figure out how to add a label to the inset map window. Consider the example below:

library(leaflet)
main_map_with_labels <- leaflet() %>%
  addTiles() %>%
  setView(lng = -121.2722, lat = 38.1341, zoom = 10) %>%
  addMiniMap(
    tiles = providers$OpenStreetMap) %>%
  addLabelOnlyMarkers(lng = -121.2722, lat = 38.1341,
    label = "Lodi") # I want to add this label to the inset
main_map_with_labels

Solution

  • If map.minimap._miniMap exists add a marker directly to that internal minimap map using the class htmlwidgets::onRender(). This function allows you to directly grab the map object using this. The leaflet map has a minimap object below which is essentially another leaflet map. So we can add markers to it using JS. I'd like to point out, that you are not meant to do this and that there can be unforseen consequences to this. addMiniMap is a plugin which is not supposed to include markers and I don't know how it will react to this.

    out

    library(leaflet)
    library(htmlwidgets)
    
    leaflet() %>%
      addTiles() %>%
      setView(lng = -121.2722, lat = 38.1341, zoom = 10) %>%
      addMiniMap(tiles = providers$OpenStreetMap) %>%
      onRender("
    function(el, x) {
      var map = this;
      if (map.minimap && map.minimap._miniMap) {
        var mini = map.minimap._miniMap;
        L.marker([38.1341, -121.2722])  // [lat, lng]
          .bindTooltip('Lodi', {permanent: true, direction: 'top'})
          .addTo(mini);
      }
    }
    ")
    

    Edit: Marker with just text

    I would like to add that this is less preferable, since it's super difficult now to tell exeactly where the marker is pointing too.

    For showing just the text, you could create a L.divIcon with some CSS

    out2

    library(leaflet)
    library(htmlwidgets)
    leaflet() %>%
      addTiles() %>%
      setView(lng = -121.2722, lat = 38.1341, zoom = 10) %>%
      addMiniMap(tiles = providers$OpenStreetMap) %>%
      onRender("
    function(el, x) {
      var map = this;
      if (map.minimap && map.minimap._miniMap) {
        var mini = map.minimap._miniMap;
        
        L.marker([38.1341, -121.2722], {
          icon: L.divIcon({
            className: 'text-label',
            html: '<div style=\"background: rgba(255,255,255,0.4); padding: 2px; border-radius: 3px; font-weight: bold;\">Lodi</div>',
            iconSize: [30, 20],
            iconAnchor: [25, 10]
          })
        }).addTo(mini);
      }
    }
    ")