Search code examples
rr-leaflet

How to automatically set the view according to one layer?


I am making some maps in Leaflet in R, and the maps consist of a polygon layer as well as a layer of markers. The polygon usually covers a larger area than the markers, but I want to zoom specifically to the marker area.

I know I can manually specify lat/longs and zoom level, but I don't want to do that because this code will generate a lot of different maps covering different subsets of my dataset (or on different datasets).

Here's a simplified version of the code that generates the map. I don't think this necessarily requires a full reprex to answer the question but can do so if necessary.

  addProviderTiles(providers$CartoDB.Positron, group = "Basemap") %>%
  addPolygons(data = seat_boundary, fillColor = "white", fillOpacity = 0.0, weight = 1.5, opacity = 0.6, color = "red", group = "Seat boundary") %>%
  addCircleMarkers(data = formalvotes_by_booth_subarea, fillColor = ~subarea_pal(sub_areas), lng=~longitude, lat=~latitude, radius = ~circle_size, fillOpacity = 1, color = 'white', opacity = 1, weight = 1.2, popup = ~popup) %>%
  addLegend(pal = subarea_pal, values = formalvotes_by_booth_subarea$sub_areas, opacity = 1)```

I also think I might be able to half-solve this problem by averaging the max and min latitude and max and min longitude in the markers dataset to come up with a central point to focus the map on, but it wouldn't ensure the zoom would be correct (indeed I'm not sure if you can set the lat/long and not set the zoom).


Solution

  • Have you tried fitBounds? Starting from what you have posted, I would first get the bbox coordinates of your markers:

    library(sf)
    
    bounds <- markers %>% 
      st_bbox() %>% 
      as.character()
    

    Then passing them into the fitBounds function:

    library(leaflet)
    
    leaflet %>%
      addPolygons(data = polygons) %>%
      addCircleMarkers(data = markers) %>%
      fitBounds(bounds[1], bounds[2], bounds[3], bounds[4])