Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export leaflet map with fixed zoom and bounding box without padding

I know that I can use mapview::mapshot to export a leaflet map from Rstudio as a PNG. I have not been, however, able to precisely specify the zoom level and region of the map to be exported.

Borrowing some code from this answer to a related question let us consider the following MWE.

library(maps)
library(ggmap)
library(maptools)
library(leaflet)
library(mapview)
library(rgdal)

country   <- 'italy';
zoomLevel <- 12;

ita.map <- map( country, fill = TRUE, col = 1, plot = F );
ita.map.ids <- sapply( strsplit( ita.map$names, ':' ), function(x) x[1] );
ita.sp <- map2SpatialPolygons( ita.map, IDs=ita.map.ids, proj4string=CRS("+proj=longlat +datum=WGS84"))

bb<-as.numeric(ita.sp@bbox)

m<-leaflet() %>%
setView(12.48,41.89,zoom=zoomLevel) %>%
  addTiles() %>%
  addPolygons(data=ita.sp)%>%
  addExtent(data=ita.sp)


mapshot(m, file = "italy.png")

results in enter image description here This is the correct zoom level but clearly does not contain all of Italy.

Adding

      %>% fitBounds(bb[1],bb[2],bb[3],bb[4])

to the code above yields enter image description here which is better, but a) does not respect the specified zoom level, and b) has a lot of unwanted horizontal padding.

I presume that adding width and height arguments to the leaflet() call would help but I am unsure how to automatically obtain the correct values. Also the resulting image would be very large necessitating a reduction in resolution.

How can I export the region of the map containing Italy at a specified zoom level without additional padding?

like image 652
Eckhard Avatar asked Oct 17 '22 08:10

Eckhard


1 Answers

I dont know that what you want is possible (zoom = 12 and all of italy)...the two things seem mutually exclusive to me... unless you have a enormous figure... as you suggested.

I dont know for certain, but maybe the answer to your padding question is in the vwidth option of webshot. I suppose your figure needs to be taller than wide, so vwidth < vheight...

mapshot(m, file = "italy.png", vwidth = 700, vheight = 744)
like image 190
user1697590 Avatar answered Oct 31 '22 00:10

user1697590