Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Boundaries of Leaflet with sf geometry in R

Tags:

r

leaflet

sf

I would like to use the sf package to extract a bounding box (e.g., st_bbox ) and pass these coords to a leaflet using fitBounds.

What is the best way to do this? There is a similar post is here: I don't want to take an average of all coordinates since we already have a bounding box that could be used AND we don't want to have to set the zoom using setView. An example of what I'm currently trying -

Taking the great state of Indiana:

require(USAboundaries);require(sf)
state <- us_boundaries(states="Indiana")
st_bbox(state)


       xmin      ymin      xmax      ymax 
    -88.11186  37.78194 -84.78395  41.75956

I'd like to get that easily into a format that Leaflet's fitBounds can interpret. Something like this perhaps?:

map.fitBounds([
  [-88.11186, 37.78194],
  [-84.78395, 41.75956]
);
like image 569
KennyC Avatar asked Feb 03 '23 22:02

KennyC


1 Answers

How about:

library(sf)
library(leaflet)
library(USAboundaries)

state <- us_boundaries(states = "Indiana")

bbox <- st_bbox(state) %>% 
  as.vector()

leaflet() %>% 
  addTiles() %>% 
  fitBounds(bbox[1], bbox[2], bbox[3], bbox[4])

enter image description here

like image 144
tyluRp Avatar answered Feb 06 '23 23:02

tyluRp