1.3 Main Functions
######### EXTRACTING Specific Amenities #########
remove_duplicates_within_threshold <- function(data, threshold) {
# Convert the distance threshold to meters
distance_threshold <- units::set_units(threshold, "meters")
# Identify pairs of points that are within the distance threshold
within_distance <- st_is_within_distance(data, data, dist = distance_threshold)
keep <- rep(TRUE, length(within_distance))
# Loop through each point and mark duplicates for removal
for (i in seq_along(within_distance)) {
if (keep[i]) {
duplicates <- within_distance[[i]]
# Mark all duplicates (excluding the current point) for removal
if (length(duplicates) > 1) {
keep[duplicates[-1]] <- FALSE
}
}
}
unique_data <- data[keep, ]
return(unique_data)
}
# Fetch OSM data for both points and polygons
fetch_osm_data <- function(key, value, bb) {
# Fetch points data and check if it exists
data_points <- tryCatch({
opq(bb = bb,timeout = 300) %>%
add_osm_feature(key = key, value = value) %>%
osmdata_sf() %>%
.$osm_points %>%
# filter(!is.na(!!sym(key))) %>%
select(geometry, !!sym(key))
}, error = function(e) {
NULL # Return NULL if points data is not available
})
# Fetch polygons data and check if it exists
data_polygons <- tryCatch({
opq(bb = bb, timeout = 300) %>%
add_osm_feature(key = key, value = value) %>%
osmdata_sf() %>%
.$osm_polygons %>%
# filter(!is.na(!!sym(key))) %>%
select(geometry, !!sym(key))
}, error = function(e) {
NULL # Return NULL if polygons data is not available
})
# Check if both points and polygons data are available
if (is.null(data_points) && is.null(data_polygons)) {
return(NULL) # Skip if no data available
}
# Convert polygons to points (centroids) if polygons are available
if (!is.null(data_polygons) && nrow(data_polygons) > 0) {
centroids_polygons <- st_centroid(data_polygons) %>%
select(geometry, !!sym(key))
} else {
centroids_polygons <- NULL
}
# Combine points and centroids if both are available
if (!is.null(data_points) && nrow(data_points) > 0 && !is.null(centroids_polygons)) {
combined <- rbind(data_points, centroids_polygons)
} else if (!is.null(data_points) && nrow(data_points) > 0) {
combined <- data_points
} else {
combined <- centroids_polygons
}
# Check that only the value of interest is present
# combined <- combined %>% filter(!!sym(key) == value)
combined <- combined %>% filter(!!sym(key) == value | is.na(!!sym(key)))
unique_combined = remove_duplicates_within_threshold(combined, 100)
return(unique_combined)
}






