【问题标题】:Getting finer control of leaflet popups in r在 r 中更好地控制传单弹出窗口
【发布时间】:2017-02-18 04:04:54
【问题描述】:

我正在尝试使用leaflet 包更好地控制R 中的leaflet 弹出窗口。 MWE 的代码如下:

library(dplyr)
library(magrittr)
library(leaflet)

download.file(
  url = "http://biogeo.ucdavis.edu/data/gadm2.8/rds/GBR_adm1.rds", 
  destfile = "GBR_adm1.rds", 
  method = "curl"
)

shp_gbr <- readRDS("GBR_adm1.rds")

# get centroids for placing popups in second map
shp_gbr_centers <- 
  rgeos::gCentroid(shp_gbr, byid = TRUE) %>% 
  sp::SpatialPointsDataFrame(shp_gbr@data, match.ID = FALSE)

shp_gbr@data %<>% 
  left_join(shp_gbr_centers[1], by = 'OBJECTID', copy = TRUE) %>% 
  rename(lat = y, lng = x) %>% 
  select(NAME_1, lat, lng) %>% 
  mutate(text = ProgGUIinR::LoremIpsum)

popup <- paste("<b><h3>", shp_gbr$NAME_1, "</h3></b>", shp_gbr$text)

shp_gbr %>% 
  leaflet() %>% 
  addPolygons(popup = ~popup)

这提供了一张漂亮的地图,其中包含在 4 个国家/地区的区域内单击时出现的弹出窗口,但在这种情况下,文本太多而无法很好地处理弹出窗口:

我想要通过addPopups 函数访问一些可用的popupOptions,在这种情况下使弹出窗口更宽并有一个滚动条。下面是一个例子:

shp_gbr %>% 
  leaflet() %>% 
  addPolygons() %>%
  addPopups(
    data = shp_gbr@data,
    popup = ~popup,
    options =
      popupOptions(
        maxWidth = 600,
        maxHeight = 100
      )
  )

但是,弹出窗口现在设置为在启动时打开,而不是在边界内点击时出现,并且一旦关闭就不会在点击时重新打开:

我的问题是如何组合这些元素,以便您可以在地图中使用滚动条来显示过多的文本,例如第一个示例,其中弹出窗口默认关闭但单击时打开。

【问题讨论】:

  • 看起来像是对 JavaScript 工作方式的保留。一种解决方法是让您的弹出式 HTML 更加强烈,并通过样式属性添加 CSS 来控制大小。
  • @alistaire 是的,你可能就在那儿......它只是非常接近,它在单独的方法中运行良好,但将它们放在一起不起作用......
  • 检查 GitHub 问题;以前可能有人遇到过这种情况。如果没有,您可以添加一个。
  • 自从this PR 已合并到开发版本中,您所追求的已经可以工作了。只需使用devtools从github安装即可
  • @TimSalabim 感谢您指出这一点 - 这正是我所希望的,只是还没有从 Github 安装最新的

标签: r leaflet


【解决方案1】:

你可以使用这个函数来创建你的弹出窗口:

popup <- paste("<div class='leaflet-popup-scrolled' style='max-width:600px;max-height:100px'><b><h3>", shp_gbr$NAME_1, "</h3></b>", shp_gbr$text,"</div>")

它将弹出窗口包装在 divleaflet-popup-scrolled 类中,以添加滚动条和内联 CSS 以设置 max-widthmax-height

【讨论】:

    猜你喜欢
    • 2018-06-22
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多