I'm looking to produce a rectangular leaflet output (i.e., aspect ratio of ~0.7). My workflow is as follows: I'm creating static maps, to be saved to image files. Then, I'll use 2 map outputs shown side-by-side in a Shiny app. This means that each output needs to be rectangular, instead of square as seems to be the default.
I tried using both fitBounds
and setMaxBounds
options with no luck. I also played with the height and width parameters of leaflet, but seemingly could not set them to an aspect ratio different from 1 (for example, width = 50%
made the map half the screen wide but also half tall; setting width = 50%, height = 75%
resulted in a blank page).
Example map:
library(leaflet)
library(webshot)
library(mapview)
df <- expand.grid(x = seq(-10, 10, 1), y = seq(-10, 10, 1))
m <- leaflet() %>%
addTiles() %>%
addMarkers(data = df, lng = ~x, lat = ~y) %>%
fitBounds(lng1 = -12, lat1 = -20, lng2 = 12, lat2 = 20)
# setMaxBounds(lng1 = -12, lat1 = -20, lng2 = 12, lat2 = 20)
mapshot(m, file = "Rplot.png")
Another way would be to use the selector
argument= "One or more CSS selectors specifying a DOM element to set the clipping rectangle to. The screenshot will contain these DOM elements". passed to webshot
library(leaflet)
df <- expand.grid(x = seq(-10, 10, 1), y = seq(-10, 10, 1))
width <- 10
height <- 4
timesPXL <- 150
m <- leaflet(
width = paste0(width*timesPXL ,"px"),
height = paste0(height*timesPXL ,"px")) %>%
addTiles() %>%
addMarkers(data = df, lng = ~x, lat = ~y) %>%
fitBounds(lng1 = -12, lat1 = -20, lng2 = 12, lat2 = 20)
mapview::mapshot(m, file = "Rplot.png", selector = ".leaflet-container")