问题
I use this R code (data was changed) to create an html file that I keep on a server:
library(leaflet)
leaflet() %>%
addProviderTiles(providers$OpenStreetMap) %>%
setView(lng=2.333333, lat=48.866667, zoom=12) %>%
addMarkers(lng=2.333333, lat=48.866667, popup='Test')
The problem is that when I render the file on a browser using a mobile phone, the pin and popup are extremely small and the size doesn't change when I zoom on the map. Is there a way to make the pin and popup bigger ?
回答1:
The idea
To achieve this, you will need to use some javascript code that you inject using the function htmlwidgets::onRender()
as mentioned on this R leaflet documentation page.
The javascript you need is some jquery code (a javascript library included with the leaflet R package) that will inject a string in the head of the generated leaflet html file to make the page responsive. Here is the javascript/jquery code :
javascript
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0">')
R implementation with reproductible code
# load leaflet library
library(leaflet)
# create the string for responsiveness that will be injected in the <head> section of the leaflet output html file. Note that the quotes were escaped using the backslash character : `\`.
responsiveness = "\'<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\'"
# build a leaflet map with a stamen background
example.map <- leaflet() %>%
addProviderTiles(group = "Stamen",
providers$Stamen.Toner,
options = providerTileOptions(opacity = 0.25)
) %>%
# add the javascript for responsivness
htmlwidgets::onRender(paste0("
function(el, x) {
$('head').append(",responsiveness,");
}"))
# show the map
example.map
# output an save the html file of the leaflet map in the root of your working directory
saveWidget(widget=example.map,
file= "example.html",
selfcontained = TRUE
)
Verification of the responsiveness of the output example.html
Now your map should be responsive. You can check this in two ways :
open the
example.html
file created with a text editor and check that the html tag<meta name="viewport" content="width=device-width, initial-scale=1.0">
is present in thehead
section of your file.open the
example.html
file in your browser. If chrome, right-click, inspect and click on the mobile phone icon to show your page as if it was rendered on a mobile phone. If yes, the zoom buttons should be easily accessible (big size).
来源:https://stackoverflow.com/questions/46453598/is-there-a-way-to-make-leaflet-map-popup-responsive-on-r