rr-mapview

How can I label points on a mapview map in r


Please help me label points on a mapview map. I can plot the points ok. I'd like to then label the points "Point A", "Point B". I'd also prefer to do this without markers for the points i.e. I'll just use the coordinates to locate the labels.

library(sf)
library(mapview)
library(tidyverse)

points <- tribble(~name, ~lat, ~lon,
                     'Point A',     -38.119151, 145.401893,
                     'Point B',     -38.127870, 145.685598)

points_sf <- st_as_sf(points, coords = c("lon", "lat"), crs = 4326)

mapview(points_sf)

Solution

  • This is supported by leaflet, for which mapview depends on - but mapview adds other behavior on-top.

    Here is the closest equivalent in mapview and how to do it exactly as requested in base leaflet.

    Note: mapview::addStaticLabels is a wrapper for leaflet::addLabelOnlyMarkers.

    library(sf)
    library(mapview)
    library(leaflet)
    library(tidyverse)
    
    points <- tribble(~name, ~lat, ~lon,
                      'Point A',     -38.119151, 145.401893,
                      'Point B',     -38.127870, 145.685598)
    
    points_sf <- st_as_sf(points, coords = c("lon", "lat"), crs = 4326)
    
    leaflet(points_sf) %>%
      addTiles() %>%
      addLabelOnlyMarkers(label =  ~name, 
                          labelOptions = labelOptions(noHide = T,
                                                      direction = 'top',
                                                      textOnly = T))
    

    enter image description here

    mapview(points_sf) %>%
      addStaticLabels(label = points$name,
                      noHide = TRUE,
                      direction = 'top',
                      textOnly = TRUE,
                      textsize = "20px")
    

    enter image description here