在 SO 或 Google 中未成功找到答案,然后自己成功找到了解决方案,我决定同时提出问题并回答。
可以在下面的“答案”中找到可重现的代码。
默认情况下,所有图层都是“可点击的”。因此,当使用多个图层时,尤其是在叠加另一个图层(例如标记和多边形)时,图层的顺序决定了可点击的内容。用多边形覆盖的标记将保持不可点击,即使没有标签伴随多边形弹出。
我发现谈论这个问题的唯一帖子是:传单地图 - 第二个多边形使第一层无法点击
天真的解决方案是确保标记最后分层。不幸的是,如果您使用诸如 之类的功能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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1677 次 |
| 最近记录: |