更好地控制R中的传单弹出窗口 [英] Getting finer control of leaflet popups in r
问题描述
我正在尝试使用leaflet
包更好地控制R
中的leaflet
弹出窗口. MWE的代码如下:
I am trying to get finer control of leaflet
popups in R
, using the leaflet
package. The code for a MWE is below:
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个国家/地区内单击时会出现的弹出窗口,但是在这种情况下,文本太多了,无法很好地处理弹出窗口:
This gives a nice map with popups that appear on clicking within the areas of the 4 countries, but in this case, the text is too much for the popup to handle nicely:
我想通过addPopups
函数访问一些可用的popupOptions
,在这种情况下,使弹出窗口更宽并具有滚动条.下面是一个示例:
What I would like is to access some of the popupOptions
available via the addPopups
function, in this case to make the popup wider and have a scroll bar. An example of this is below:
shp_gbr %>%
leaflet() %>%
addPolygons() %>%
addPopups(
data = shp_gbr@data,
popup = ~popup,
options =
popupOptions(
maxWidth = 600,
maxHeight = 100
)
)
但是,现在将弹出窗口设置为在启动时打开,而不是在边界内单击时显示,并且一旦关闭就不会在单击时重新打开:
However, the popups are now set to be open on launch, rather than appearing on clicking within the boundaries, and do not reopen on click once closed:
我的问题是如何组合这些元素,以便您可以在地图中(例如第一个示例)使用滚动条来显示太多文本,默认情况下,弹出式窗口处于关闭状态,但单击时会打开. >
My question is how to combine these elements so that you could have, say, a scroll bar for too much text within a map such as the first example, where the popups are closed by default but open on click.
推荐答案
您可以使用此函数创建弹出窗口:
You could use this function to create your popup:
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>")
它使用leaflet-popup-scrolled
类将弹出窗口包装在div
中,以添加滚动条和内联CSS来设置max-width
和max-height
.
It wraps the popup in a div
with the leaflet-popup-scrolled
class to add the scroll bar and inline CSS to set the max-width
and max-height
.
这篇关于更好地控制R中的传单弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!