Hello,
I am trying to crop/trim a spatial vector based on another. The code is as follows, and comments explain what is the purpose:
# libraries we need
libs <- c(
"tidyverse", "sf", "osmdata",
"terra"
)
# install missing libraries
installed_libs <- libs %in% rownames(installed.packages())
if (any(installed_libs == F)) {
install.packages(libs[!installed_libs])
}
# load libraries
invisible(lapply(libs, library, character.only = T))
# 2. GET LISBON BOUNDARIES FROM OSM DATA - Retrieve OSM data
#--------------------------------------
city <- "Lisbon, Portugal"
# define longlat projection
crsLONGLAT <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# retrieves a list
lisbon_city_border <- osmdata::getbb(
city,
format_out = "sf_polygon"
)
lisbon_border <- lisbon_city_border[[1]] |> # lisbon_city_border[[2]] : Lisbon district
sf::st_set_crs(crsLONGLAT) |>
sf::st_transform(crsLONGLAT)
# check if its everything right
terra::plot(lisbon_border)
# Problems to solve:
# Problem 1 - If I use trim_osmdata(lisbon_border) certain polygons disappear where they were intended to exist
# Problem 2 - It was suppose to have only "park", "nature_reserve", "golf_course, but "playground", "fitness", pitch, dog, also appear
# Get the data from OSM
greensp_osm_query <-
# start query, input bounding box
opq(bbox = lisbon_city_border) %>%
# we want to extract "leisure" features that are park, nature reserve or a golf course
add_osm_feature(key = "leisure",
value = c("park", "nature_reserve", "golf_course")) %>%
# query OSM and return as simple features (sf)
osmdata_sf()
# Convert POLYGON to MULTIPOLYGON and bind into one sf object. Both contain information.
greensp_sf_box <- bind_rows(st_cast(greensp_osm_query$osm_polygons, "MULTIPOLYGON"),
greensp_osm_query$osm_multipolygons) %>%
select(name, osm_id, leisure)
terra::plot(greensp_sf_box["leisure"])
# How to limit data to Lisbon boundaries instead of the rectangular bounding box?
# ----> Some polygons disappear .......
greensp_osm <- greensp_osm_query %>%
trim_osmdata(lisbon_border) # Applying makes polygons disappear
# Convert POLYGON to MULTIPOLYGON and bind into one sf object. Both contain information.
greensp_sf <- bind_rows(st_cast(greensp_osm$osm_polygons, "MULTIPOLYGON"),
greensp_osm$osm_multipolygons) %>%
select(name, osm_id, leisure)
terra::plot(greensp_sf["leisure"]) # More than the values selected are presented?
Basically, the plots I get are the following:
1)
2) While trimmed there are polygons that disappear. As you may notice by this plot:
What am I doing wrong?
Another question: while retrieving values from OSM, more specifically, "park", "nature_reserve", "golf_course", why does other values appear ?
I would greatly appreciate your help in solving these problems.
Thank you very much,
Luis Barqueira