Search code examples
geospatialopenstreetmapr-sfcoordinate-systems

How to retrieve bbox for osmdata from spatial feature?


How to define the bbox to download OSM data based on the extent of a spatial file? The following example returns an error message:

...the only allowed values are floats between -90.0 and 90.0

This shows that the bbox-values are out of allowed range. It also shows that the convertion between NAD27 and EPSG:3857 did not return the spatial data at place where it should be. With other spatial data I had similar problems. Eventhough within allowed range, the data didn't appear at the expected place. Downloaded OSM data appeared at a different place as the input spatial file.

library(sf)
library(raster)
library(osmdata)

osm_proj <-("+init=epsg:3857")

nc <- st_read(system.file("shape/nc.shp", package="sf"))

nc <- st_transform(nc, osm_proj)

bbox.nc <- as.vector(extent(nc[22,]))/100000

q <- opq(bbox = bbox.nc) %>%
  add_osm_feature(key = 'natural', value = 'water')

osm.water <- osmdata_sf(q)

How to prepare the bbox that downloaded OSM data matches spatial extend of input spatial file?


Solution

  • OSM works in lat-lon, which means EPSG:4326. You need to transform the coordinates accordingly. You also don't need raster::extent(); sf::st_bbox() will be sufficient in this use case.

    Or in your context consider this code; as this is only a toy example I am not using the whole NC state, but a single county (otherwise errors on timeout may occur, which would be a separate kind of a problem - this question is about bounding boxes).

    library(sf)
    library(osmdata)
    
    nc <- st_read(system.file("shape/nc.shp", package="sf"))
    
    strelitz <- st_transform(nc, 4326) %>% 
      dplyr::filter(NAME == "Mecklenburg") # as in Charlotte of Mecklenburg-Strelitz
      
    
    q <- opq(bbox = sf::st_bbox(strelitz)) %>%
      add_osm_feature(key = 'natural', value = 'water') %>% 
      osmdata_sf()
    
    plot(st_geometry(strelitz))
    plot(st_geometry(q$osm_lines), col = 'blue', add = T)
    

    mecklenburg county & its waters

    A shameles plug: I wrote about querying OSM for points of interest a while back, you may find this post interesting :)

    https://www.jla-data.net/eng/finding-pois-along-a-route/