I'm attempting to label polygons based on information within the spatial dataframe. Leveraging an example for points (the last example here) I've attempted the following:
leaflet(mapview::gadmCHE) %>% addPolygons(fillOpacity = 0.5, fillColor = "white", weight = 1,
label = mapply(function(x, y) {
HTML(sprintf("<em>%s:</em>%s", htmlEscape(x), htmlEscape(y)))},
mapview::gadmCHE$NAME_0, mapview::gadmCHE$NAME_1, SIMPLIFY = F),
labelOptions = lapply(1:nrow(houses), function(x) {
labelOptions(direction='auto')
})
I only see a horizontal line. My goal is to slightly "prettify" the labels for some polygons.
I'm not sure why that doesn't work, but this does:
library(htmltools)
leaflet(mapview::gadmCHE) %>%
addPolygons(fillOpacity = 0.5, fillColor = "white", weight = 1,
label = ~sprintf("<em>%s:</em> %s", htmlEscape(NAME_0), htmlEscape(NAME_1)) %>% lapply(HTML),
labelOptions = labelOptions(direction='auto')
)
It's really annoying that HTML() collapses the string vector, we really need pHTML() or something that marks each individual element as HTML...
On a side note, you don't need to supply a list for labelOptions unless you want to apply a different labelOption for each marker/shape.
Thank you both - I discovered after posting that there was something odd specifically with the mapply of the HTML() on that particular dataset (and the one I'm working with) and almost deleted this issue.
Is there a way to add static labels to addPolygons? I want the labels to already be on the map and not just appear when I hover over. The noHide attribute doesn't seem to work.
@jakeander You will have to determine the coordinates for a proper point within each polygon and use addLabelOnlyMarkers. This is necessary as leaflet has no way of knowing where to put a static label in case of a polygon.
You can use GISTools::poly.labels or rgeos::polygonLabel functions to get optimal points, and then pass them to addLabelOnlyMarkers.
poly.labels proved to be extremely useful. This was bugging me for a while. Appreciate the help!
Most helpful comment
@jakeander You will have to determine the coordinates for a proper point within each polygon and use
addLabelOnlyMarkers. This is necessary as leaflet has no way of knowing where to put a static label in case of a polygon.You can use
GISTools::poly.labelsorrgeos::polygonLabelfunctions to get optimal points, and then pass them toaddLabelOnlyMarkers.