在 SO 或 Google 中未成功找到答案,然后自己成功找到了解决方案,我决定同时提出问题并回答。
可以在下面的“答案”中找到可重现的代码。
问题
默认情况下,所有图层都是“可点击的”。因此,当使用多个图层时,尤其是在叠加另一个图层(例如标记和多边形)时,图层的顺序决定了可点击的内容。用多边形覆盖的标记将保持不可点击,即使没有标签伴随多边形弹出。
我发现谈论这个问题的唯一帖子是:Leaflet Map - second Polygon makes the first layer unclickable
天真的解决方案是确保标记最后分层。不幸的是,如果您使用 addLayersControl()
之类的函数,启用/禁用图层会将该图层移到前面。因此,虽然层顺序最初很重要,但它并不能真正“解决”问题。
最佳答案
解决方案
相应地使用函数 pathOptions()
、 markerOptions()
和 labelOptions()
。
就我而言,是多边形层导致了问题。通过执行 addPolygons(..., options = pathOptions(clickable = FALSE))
将这些设置为“不可点击”。
例子
library(rgdal) # for spatial data
library(leaflet)
library(dplyr)
library(magrittr)
# download and load state border data
url <- "http://www2.census.gov/geo/tiger/GENZ2015/shp/cb_2015_us_state_5m.zip"
temp <- tempfile(fileext = '.zip')
download.file(url, temp)
unzip(temp, exdir = dirname(temp))
states <- rgdal::readOGR(file.path(dirname(temp), "cb_2015_us_state_5m.shp"),
layer = "cb_2015_us_state_5m", verbose = FALSE)
unlink(temp)
# code adopted from https://rstudio.github.io/leaflet/shapes.html
neStates <- subset(states, states$STUSPS %in% c(
"CT","ME","MA","NH","RI","VT","NY","NJ","PA"
))
cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))
# (1) polygon layer added last; cannot click cities/circles
map_1 <- leaflet(neStates) %>%
addProviderTiles("CartoDB.Positron") %>%
addCircles(data = cities, lng = ~Long, lat = ~Lat, weight = 1,
radius = ~sqrt(Pop) * 30, popup = ~City,
group = "Cities") %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.2, smoothFactor = 0.5,
color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
group = "States") %>%
addLayersControl(overlayGroups = c('Cities', 'States'),
options = layersControlOptions(collapsed = FALSE))
# (2) polygon layer made 'unclickable' (clickable = FALSE)
map_2 <- leaflet(neStates) %>%
addProviderTiles("CartoDB.Positron") %>%
addCircles(data = cities, lng = ~Long, lat = ~Lat, weight = 1,
radius = ~sqrt(Pop) * 30, popup = ~City,
group = "Cities") %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.2, smoothFactor = 0.5,
color = ~colorQuantile("YlOrRd", states$AWATER)(AWATER),
group = "States",
options = pathOptions(clickable = FALSE)) %>% # DISABLE 'clickable'
addLayersControl(overlayGroups = c('Cities', 'States'),
options = layersControlOptions(collapsed = FALSE))
map_1 # even if polygon layer is put last, disable/enable layer puts it in front again
map_2 # disable/enabling any layer has no impact!
关于r - 在不重新排序的情况下使传单层可点击或不可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399656/