Leaflet map margins

Hello, I am producing maps showing catchment populations for GP practices in a loop using leaflet. I want the map to have a consistent size around the output areas covered by the GP practice. I attach some examples showing the variation.

The code I am using is:
n <- leaflet() %>% addTiles() %>%
addPolygons(data = j, color = "#000000", weight = 1, fillColor = "#2E8B57", fillOpacity = 1) %>%
addPolygons(data = ccg_br, color = "#000000", weight = 3, fillOpacity = 0.1) %>%
addAwesomeMarkers(lng = coord$long, lat = coord$lat)

The first polygon creates the green, the second the surrounding black line.
I am saving the maps as png.
How might I reset the size of the polygons to fill the view as in the second example?
Many thanks

You can set the fitBounds() call to force the map to the extent of bounding box of a specific polygon.

Note though that the zoom level is discrete, not continuous. So there will be some zoom levels that are not achievable.

As I do not have access to your polygons consider this example, built on the well known & well loved North Carolina shapefile from {sf}.


carolina <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = T) %>% 

durham_cnty <- subset(carolina, NAME == "Durham")

bbox_dur <- st_bbox(durham_cnty) %>%  # bounding box of the polygon of interest

leaflet(carolina) %>% # this need not be the same object as the polygon of interest...
   addProviderTiles("Stamen.Toner") %>% 
   addPolygons() %>% 
   fitBounds(lng1 = bbox_dur[1], 
             lat1 = bbox_dur[2],
             lng2 = bbox_dur[3],
             lat2 = bbox_dur[4])


Thanks Jlacko, that really helped. I appreciate your fast response

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.