13

I am working with the leaflet R package. I have a zoning system made of polygons and I'd like to lay their IDs on top of them. Below is an illustration (with another software) of my objective.

enter image description here

Thanks for your suggestions!

MLavoie
  • 9,671
  • 41
  • 36
  • 56
wrocg
  • 145
  • 1
  • 1
  • 4

1 Answers1

21

Since there is no reproducible data, I decided to use one of my previous posts related to leaflet. There are two things you want to take away from this post: 1) you need to create a data frame containing center points of target regions, 2) you need to use addLabelOnlyMarkers(). You can achieve the first thing using gCentroid(). I added row names of the polygon data set (UK) as character to centers. This is used for labeling. You need to think what labels you use in your own case. Once this data set is ready, you want to use it in addLabelOnlyMarkers().

library(raster)
library(rgeos)
library(leaflet)

# Get UK polygon data
UK <- getData("GADM", country = "GB", level = 2)

# Find a center point for each region
centers <- data.frame(gCentroid(UK, byid = TRUE))
centers$region <- row.names(UK)

### Create dummy data
set.seed(111)
mydf <- data.frame(place = unique(UK$NAME_2),
                   value = sample.int(n = 1000, size = n_distinct(UK$NAME_2), replace = TRUE))

### Create five colors for fill
mypal <- colorQuantile(palette = "RdYlBu", domain = mydf$value, n = 5, reverse = TRUE)

leaflet() %>% 
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 55, lng = -3, zoom = 6) %>%
addPolygons(data = UK,
            stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
            fillColor = ~mypal(mydf$value),
            popup = paste("Region: ", UK$NAME_2, "<br>",
                          "Value: ", mydf$value, "<br>")) %>%
addLabelOnlyMarkers(data = centers,
                    lng = ~x, lat = ~y, label = ~region,
                    labelOptions = labelOptions(noHide = TRUE, direction = 'top', textOnly = TRUE)) %>%
addLegend(position = "bottomright", pal = mypal, values = mydf$value,
          title = "UK value",
          opacity = 0.3)

enter image description here

jazzurro
  • 23,179
  • 35
  • 66
  • 76
  • 2
    This is a beautiful example, thank you. I would also like to link to this answer which I found very helpful for non convex polygons: https://gis.stackexchange.com/a/265475/78424 – geneorama Dec 31 '19 at 21:22
  • @geneorama Thanks for your words. Much appreciated! Thanks for leaving a useful link here as well. – jazzurro Dec 31 '19 at 22:38
  • @jazzurro, great answer. How to change font size when zooming in/out. When the labels are names it becomes weird when zooming out. Is there a way to change the font size or make the text label disappear? – Paulo Marques Dec 07 '22 at 18:29