2
votes

i need to setView of leaflet map to new polygon add in the map:

    observeEvent(input$do, {

    shapeComuna = paste0("cl_",input$interval,"comunas_geo")
    archComuna = paste0("shapefiles/cl_",input$interval,"comunas_geo")
    comuna <- readOGR(dsn = archComuna, layer = shapeComuna)
    names(comuna)[1] <- "ID"
    shapeData2 <- spTransform(comuna, CRS("+proj=longlat +ellps=GRS80"))

    proxy <- leafletProxy("mymap") 
    proxy %>% clearShapes() %>%  addPolygons(
      data = shapeData2,
      smoothFactor = 0.3,
      fillOpacity = 0.45,
      stroke = TRUE,
      opacity = 1,
      weight = 1.8,
      popup = shapeData2$NOMBRE,
      layerId = shapeData2$ID,
      group = "Comunas"
    ) %>% setView()
})

When i click in input$do, clear all polygons and print the new one, but i canĀ“t set the view of that new polygon dynamically.

Exist one form for searching that new polygon and set the view in him ? Or need to take one point of the shapefile and pass it to setView ?

1

1 Answers

0
votes

You can indeed fetch the bounds from the shape file, see Here.

So in your code you could do something like this:

df = do.call(rbind,lapply(shapeData2, function(x) 
        {data.frame(lon = c(min(x$coords[,1]),max(x$coords[,1])),lat = c(min(x$coords[,2]),max(x$coords[,2]))})

and then use

map %>% fitBounds(min(df$lon), min(df$lat), max(df$lon), max(df$lat))

to modify the bounds of the mpa coordingly. Note: Since I was not bale tot est this code due to the lack of a reproducible example, but it may point you in the right direction.