R Leaflet: Passing popupOptions when adding Polygo

2019-07-19 09:25发布

问题:

Within addPolygons() there is a popup parameter just like the one in the addPopups() function. The difference (I think) is that when the popup is created within addPolygons(), one can click anywhere within the polygon to trigger the popup, but if addPopups() is used, a single lng and lat point must be defined.

I want to change one of the default options (maxWidth) in popupOptions() which can easily be done when using addPopups() because it contains the parameter options = popupOptions() but I don't know how to do it when using addPolygons(); within that function the options parameter is options = pathOptions().

Below is a reproducible example from the leaflet documentation with a popup added that I'd like increase the maxWidth.

library(rgdal)

# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states <- readOGR("shp/cb_2013_us_state_20m.shp",
  layer = "cb_2013_us_state_20m", verbose = FALSE)

neStates <- subset(states, states$STUSPS %in% c(
  "CT","ME","MA","NH","RI","VT","NY","NJ","PA"
))

leaflet(neStates) %>%
  addPolygons(
    stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
    color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
    popup="<b>Hello World</b>"
  )

回答1:

You can do this simply by adding popupOptions() after your popup in the addPloygons() block like so:

leaflet(neStates) %>%
    addPolygons(
        stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
        color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
        popup="<b>Hello World</b>"
        popupOptions = popupOptions(maxWidth ="100%", closeOnClick = TRUE)

)

Here is the list from the PDF vignette on leaflet R of all the things you can drop in the popupOptions() list:

popupOptions(maxWidth = 300, minWidth = 50, maxHeight = NULL,
            autoPan = TRUE, keepInView = FALSE, closeButton = TRUE,
             zoomAnimation = TRUE, closeOnClick = NULL, className = "", ...)


标签: r leaflet