ropensci / osmdata

R package for downloading OpenStreetMap data
https://docs.ropensci.org/osmdata
317 stars 45 forks source link

cannot project multi-polygons #102

Closed lrob closed 6 years ago

lrob commented 7 years ago

Hallo everybody,

I experienced some problems while trying to project data downloaded via the osmdata library (I'm using osmdata 0.0.5).

I downloaded some spatial information from osm with the following command:

dat1 <- opq(bbox = 'Kunming, China') %>%
  add_osm_feature(key = 'natural', value = 'water') %>%
  osmdata_sp ()

I would like to project the downloaded data in EPGS:3035. Everything works fine with polygons:

polygonProj <- spTransform(dat1$osm_polygons, CRS( "+init=epsg:3035" ))

The same does not work with multipolygons. The following command

multipolygonProj <- spTransform(dat1$osm_multipolygons, CRS( "+init=epsg:3035" ))

issues this error: Error in Polygons(output, ID) : Single ID required

This happens because the multipolygons returned by the osmdata_sp function are associated to a vector of strings rather than a single string.

In order to find a workaround I created a string ID for each multiploygon with the following commands:

p <- function(x){
  x@ID <- paste0(x@ID, collapse="")
  return(x)
}
multipolygon@polygons <- lapply(multipolygon@polygons, FUN = p)

After this transformation the following command ended without errors

multipolygonProj <- spTransform(dat1$osm_multipolygons, CRS( "+init=epsg:3035" ))

However I incurred in another problem, the hole and the ringDir slots values are not preserved during the transformation.

Am I correctly using the spTransform and osmdata_sp functions? If it is the case, are these problems of the spTransform function or problems deriving from the data structure returned by the osmdata_sp function?

Thanks in advance Roberto

mpadge commented 7 years ago

Thanks Roberto - These are indeed likely to be problems induced by the osmdata_sp() function. osmdata names all objects according to OSM structures, which is not expected by sf/sp objects. This certainly causes some issues with sf compatibility, but I've not yet checked for sp. I'll have a look at get back to you.

mpadge commented 6 years ago

That's a great catch - thanks! The problem was with the plotOrder slot of the multipolygon components. It should now work, and i've also de-vectorized the polygon names with this commit. You should now be able to do this with no errors:

dat1 <- opq(bbox = 'Kunming, China') %>%
  add_osm_feature(key = 'natural', value = 'water') %>%
  osmdata_sp ()
multipolygonProj <- spTransform(dat1$osm_multipolygons, CRS( "+init=epsg:3035" ))