在SO或Google中找不到答案,然后我自己成功找到解决方案,我决定同时提出问题并立即回答。
可以在“答案”中找到可重现的代码。
默认情况下,所有图层都是“可点击的”。因此,当使用多个图层时,特别是在覆盖另一个图层时(例如标记和多边形),图层的顺序决定了可点击的内容。覆盖多边形的标记将保持不可点,即使多边形没有弹出标签。
我发现谈论此问题的唯一帖子是:Leaflet Map - second Polygon makes the first layer unclickable
天真的解决方案是确保标记最后分层。不幸的是,如果您使用addLayersControl()
之类的功能,启用/禁用图层会将该图层移到前面。因此,虽然图层顺序最初 ,但它并没有真正“解决”问题。
答案 0 :(得分:3)
相应地使用功能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!